SpringBoot系列八:SpringBoot整合消息服务(SpringBoot 整合 ActiveMQ、SpringBoot 整合 RabbitMQ、SpringBoot 整合 Kafka)...

浅浅的花香味﹌ 2021-09-29 04:26 684阅读 0赞

声明:本文来源于MLDN培训视频的课堂笔记,写在这里只是为了方便查阅。

1、概念:SpringBoot 整合消息服务

2、具体内容

对于异步消息组件在实际的应用之中会有两类:

· JMS:代表作就是 ActiveMQ,但是其性能不高,因为其是用 java 程序实现的;

· AMQP:直接利用协议实现的消息组件,其大众代表作:RabbitMQ,高性能代表作:Kafka。

2.1、SpringBoot 整合 ActiveMQ

1、 如果要想在项目之中去使用 ActiveMQ 组件,则应该为项目添加依赖支持库,修改 pom.xml 配置文件:

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-activemq</artifactId>
  4. </dependency>

2、 修改 application.yml 配置文件进行 activemq 的配置;

  1. server:
  2. port: 80
  3. spring:
  4. messages:
  5. basename: i18n/Messages,i18n/Pages
  6. jms:
  7. pub-sub-domain: false # 配置消息的类型,如果是true则表示为topic消息,如果为false表示Queue消息
  8. activemq:
  9. user: studyjava # 连接用户名
  10. password: hello # 连接密码
  11. broker-url: tcp://activemq-server:61616 # 消息组件的连接主机信息

3、 随后定义一个消息的消费者,消费者主要是进行一个监听控制,在 SpringBoot 里面可以直接利用注解@JmsListener进行监听:

  1. package cn.study.microboot.consumer;
  2. import org.springframework.jms.annotation.JmsListener;
  3. import org.springframework.stereotype.Service;
  4. @Service
  5. public class MessageConsumerService {
  6. @JmsListener(destination="study.msg.queue")
  7. public void receiveMessage(String text) { // 进行消息接收处理
  8. System.err.println("【*** 接收消息 ***】" + text);
  9. }
  10. }

4、 随后建立消息的发送者服务,一般而言如果进行消息的发送往往会准备出一个业务接口来:

  1. package cn.study.microboot.producer;
  2. public interface IMessageProducerService {
  3. public void sendMessage(String msg) ;
  4. }

5、 随后建立一个配置程序类,定义 ActiveMQ 的消息发送模版处理类:

  1. package cn.study.microboot.config;
  2. import javax.jms.Queue;
  3. import org.apache.activemq.command.ActiveMQQueue;
  4. import org.springframework.context.annotation.Bean;
  5. import org.springframework.context.annotation.Configuration;
  6. import org.springframework.jms.annotation.EnableJms;
  7. @Configuration
  8. @EnableJms
  9. public class ActiveMQConfig {
  10. @Bean
  11. public Queue queue() {
  12. return new ActiveMQQueue("study.msg.queue") ;
  13. }
  14. }

6、 创建消息发送的子类实现消息发送处理:

  1. package cn.study.microboot.producer.impl;
  2. import javax.annotation.Resource;
  3. import javax.jms.Queue;
  4. import org.springframework.jms.core.JmsMessagingTemplate;
  5. import org.springframework.stereotype.Service;
  6. import cn.study.microboot.producer.IMessageProducerService;
  7. @Service
  8. public class MessageProducerServiceImpl implements IMessageProducerService {
  9. @Resource
  10. private JmsMessagingTemplate jmsMessagingTemplate;
  11. @Resource
  12. private Queue queue;
  13. @Override
  14. public void sendMessage(String msg) {
  15. this.jmsMessagingTemplate.convertAndSend(this.queue, msg);
  16. }
  17. }

7、 编写测试类来观察消息的处理:

  1. package cn.study.microboot.test;
  2. import javax.annotation.Resource;
  3. import org.junit.Test;
  4. import org.junit.runner.RunWith;
  5. import org.springframework.boot.test.context.SpringBootTest;
  6. import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
  7. import org.springframework.test.context.web.WebAppConfiguration;
  8. import cn.study.microboot.StartSpringBootMain;
  9. import cn.study.microboot.producer.IMessageProducerService;
  10. @SpringBootTest(classes = StartSpringBootMain.class)
  11. @RunWith(SpringJUnit4ClassRunner.class)
  12. @WebAppConfiguration
  13. public class TestActiveMQ {
  14. @Resource
  15. private IMessageProducerService messageProducer;
  16. @Test
  17. public void testSend() throws Exception {
  18. for (int x = 0; x < 10; x++) {
  19. this.messageProducer.sendMessage("study - " + x);
  20. }
  21. }
  22. }

基于 SpringBoot 配置的 JMS 的组件访问整体的处理十分简单

2.2、SpringBoot 整合 RabbitMQ

如果要进行 RabbitMQ 整合的时候一定要注意以下几个概念:交换空间、虚拟主机、队列信息。本次为了方便起见将项目分为 两个:RabbitMQ-Consumer、RabbitMQ-Producer。

1、 【两个项目】将 rabbitmq 的依赖支持包拷贝到项目之中;

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-amqp</artifactId>
  4. </dependency>

2、 【microboot-rabbitmq-producer、microboot-rabbitmq-consumer】修改 application.yml 配置文件,追加 rabbitmq 的相关配置项:

  1. server:
  2. port: 80
  3. spring:
  4. messages:
  5. basename: i18n/Messages,i18n/Pages
  6. rabbitmq:
  7. addresses: rabbitmq-server
  8. username: studyjava
  9. password: hello
  10. virtual-host: /

3、 【microboot-rabbitmq-producer】建立一个消息的发送接口:

  1. package cn.study.microboot.producer;
  2. public interface IMessageProducerService {
  3. public void sendMessage(String msg) ;
  4. }

4、 【microboot-rabbitmq-producer】为了可以正常使用 RabbitMQ 进行消息处理,你还需要做一个消息生产配置类;

  1. package cn.study.microboot.config;
  2. import org.springframework.amqp.core.Binding;
  3. import org.springframework.amqp.core.BindingBuilder;
  4. import org.springframework.amqp.core.DirectExchange;
  5. import org.springframework.amqp.core.Queue;
  6. import org.springframework.context.annotation.Bean;
  7. import org.springframework.context.annotation.Configuration;
  8. @Configuration
  9. public class ProducerConfig {
  10. public static final String EXCHANGE = "study.microboot.exchange"; // 交换空间名称
  11. public static final String ROUTINGKEY = "study.microboot.routingkey"; // 设置路由key
  12. public static final String QUEUE_NAME = "study.microboot.queue"; // 队列名称
  13. @Bean
  14. public Binding bindingExchangeQueue(DirectExchange exchange,Queue queue) {
  15. return BindingBuilder.bind(queue).to(exchange).with(ROUTINGKEY) ;
  16. }
  17. @Bean
  18. public DirectExchange getDirectExchange() { // 使用直连的模式
  19. return new DirectExchange(EXCHANGE, true, true);
  20. }
  21. @Bean
  22. public Queue queue() { // 要创建的队列信息
  23. return new Queue(QUEUE_NAME);
  24. }
  25. }

5、 【microboot-rabbitmq-producer】创建消息服务的实现子类:

  1. package cn.study.microboot.producer.impl;
  2. import javax.annotation.Resource;
  3. import org.springframework.amqp.rabbit.core.RabbitTemplate;
  4. import org.springframework.stereotype.Service;
  5. import cn.study.microboot.config.ProducerConfig;
  6. import cn.study.microboot.producer.IMessageProducerService;
  7. @Service
  8. public class MessageProducerServiceImpl implements IMessageProducerService {
  9. @Resource
  10. private RabbitTemplate rabbitTemplate;
  11. @Override
  12. public void sendMessage(String msg) {
  13. this.rabbitTemplate.convertAndSend(ProducerConfig.EXCHANGE,
  14. ProducerConfig.ROUTINGKEY, msg);
  15. }
  16. }

6、 【microboot-rabbitmq-consumer】依然需要做一个消费者的配置程序类,而这个程序类里面主要的目的依然是设置交换空间、 路由 KEY 等信息。

  1. package cn.study.microboot.config;
  2. import org.springframework.amqp.core.Binding;
  3. import org.springframework.amqp.core.BindingBuilder;
  4. import org.springframework.amqp.core.DirectExchange;
  5. import org.springframework.amqp.core.Queue;
  6. import org.springframework.context.annotation.Bean;
  7. import org.springframework.context.annotation.Configuration;
  8. @Configuration
  9. public class ConsumerConfig {
  10. public static final String EXCHANGE = "study.microboot.exchange"; // 交换空间名称
  11. public static final String ROUTINGKEY = "study.microboot.routingkey"; // 设置路由key
  12. public static final String QUEUE_NAME = "study.microboot.queue"; // 队列名称
  13. @Bean
  14. public Queue queue() { // 要创建的队列信息
  15. return new Queue(QUEUE_NAME);
  16. }
  17. @Bean
  18. public DirectExchange getDirectExchange() { // 使用直连的模式
  19. return new DirectExchange(EXCHANGE, true, true);
  20. }
  21. @Bean
  22. public Binding bindingExchangeQueue(DirectExchange exchange,Queue queue) {
  23. return BindingBuilder.bind(queue).to(exchange).with(ROUTINGKEY) ;
  24. }
  25. }

7、 【microboot-rabbitmq-consumer】实现监听处理类:

  1. package cn.study.microboot.consumer;
  2. import org.springframework.amqp.rabbit.annotation.RabbitListener;
  3. import org.springframework.stereotype.Service;
  4. @Service
  5. public class MessageConsumerService {
  6. @RabbitListener(queues="study.microboot.queue")
  7. public void receiveMessage(String text) { // 进行消息接收处理
  8. System.err.println("【*** 接收消息 ***】" + text);
  9. }
  10. }

8、 【microboot-rabbitmq-producer】创建一个测试类实现消息的发送处理。

  1. package cn.study.microboot.test;
  2. import javax.annotation.Resource;
  3. import org.junit.Test;
  4. import org.junit.runner.RunWith;
  5. import org.springframework.boot.test.context.SpringBootTest;
  6. import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
  7. import org.springframework.test.context.web.WebAppConfiguration;
  8. import cn.study.microboot.StartSpringBootMain;
  9. import cn.study.microboot.producer.IMessageProducerService;
  10. @SpringBootTest(classes = StartSpringBootMain.class)
  11. @RunWith(SpringJUnit4ClassRunner.class)
  12. @WebAppConfiguration
  13. public class TestActiveMQ {
  14. @Resource
  15. private IMessageProducerService messageProducer;
  16. @Test
  17. public void testSend() throws Exception {
  18. for (int x = 0; x < 100; x++) {
  19. this.messageProducer.sendMessage("study - " + x);
  20. }
  21. }
  22. }

9、 【microboot-rabbitmq-consumer】编写消息接收测试类,这里面不需要编写代码,只需要做一个休眠即可:

  1. package cn.study.microboot;
  2. import org.junit.Test;
  3. import org.junit.runner.RunWith;
  4. import org.springframework.boot.test.context.SpringBootTest;
  5. import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
  6. import org.springframework.test.context.web.WebAppConfiguration;
  7. @SpringBootTest(classes = StartSpringBootMain.class)
  8. @RunWith(SpringJUnit4ClassRunner.class)
  9. @WebAppConfiguration
  10. public class AppTest {
  11. @Test
  12. public void testStart() throws Exception {
  13. Thread.sleep(Long.MAX_VALUE);
  14. }
  15. }

整体进行项目开发之中整合的处理步骤还是简单,但是千万要注意,由于是第一次整合处理,所以将生产者与消费者的配置 类分开了,实际上这两个类的作用是完全一样的。

2.3、SpringBoot 整合 Kafka

Kafka 是现在最好的开源消息组件,其仿照 AMQP 协议操作,而且处理的性能也是最高的。本次使用已经配置好的 Kafka 服 务器,而且这台服务器上使用了 kerberos 认证,所以应该首先准备好一个 jass 配置文件:

1、 定义“kafka_client_jaas.conf”配置文件:

  1. KafkaClient {
  2. org.apache.kafka.common.security.plain.PlainLoginModule required
  3. username="bob"
  4. password="bob-pwd";
  5. };

2、 为了方便进行项目的观察, 本次依然准备出了两个项目:生产者( microboot-kafka-producer )、 消 费 者 (microboot-kafka-consumer),随后为这两个项目添加 kafka 配置支持:

  1. <dependency>
  2. <groupId>org.springframework.kafka</groupId>
  3. <artifactId>spring-kafka</artifactId>
  4. </dependency>

3、 【micorboot-kafka-consumer】修改 application.yml 配置文件,进行 kafka 配置项编写:

  1. server:
  2. port: 80
  3. spring:
  4. messages:
  5. basename: i18n/Messages,i18n/Pages
  6. kafka:
  7. bootstrap-servers:
  8. - kafka-single:9095
  9. template:
  10. default-topic: mldn-microboot
  11. consumer:
  12. key-deserializer: org.apache.kafka.common.serialization.StringDeserializer
  13. value-deserializer: org.apache.kafka.common.serialization.StringDeserializer
  14. group-id: group-1
  15. properties:
  16. sasl.mechanism: PLAIN
  17. security.protocol: SASL_PLAINTEXT

4、 【micorboot-kafka-consumer】建立一个 Kafka 的消息的消费程序类:

  1. package cn.study.microboot.consumer;
  2. import org.apache.kafka.clients.consumer.ConsumerRecord;
  3. import org.springframework.kafka.annotation.KafkaListener;
  4. import org.springframework.stereotype.Service;
  5. @Service
  6. public class MessageConsumerService {
  7. @KafkaListener(topics = {"study-microboot"})
  8. public void receiveMessage(ConsumerRecord<String, String> record) { // 进行消息接收处理
  9. System.err.println("【*** 接收消息 ***】key = " + record.key() + "、value = "
  10. + record.value());
  11. }
  12. }

5、 【micorboot-kafka-consumer】随后还需要修改 SpringBoot 的启动程序类,追加 kerberos 配置:

  1. package cn.study.microboot;
  2. import org.springframework.boot.SpringApplication;
  3. import org.springframework.boot.autoconfigure.SpringBootApplication;
  4. @SpringBootApplication // 启动SpringBoot程序,而后自带子包扫描
  5. public class StartSpringBootMain {
  6. static {
  7. System.setProperty("java.security.auth.login.config",
  8. "d:/kafka_client_jaas.conf"); // 表示系统环境属性
  9. }
  10. public static void main(String[] args) throws Exception {
  11. SpringApplication.run(StartSpringBootMain.class, args);
  12. }
  13. }

6、 【microboot-kafka-producer】修改 application.yml 配置文件:

  1. server:
  2. port: 80
  3. spring:
  4. messages:
  5. basename: i18n/Messages,i18n/Pages
  6. kafka:
  7. bootstrap-servers:
  8. - kafka-single:9095
  9. template:
  10. default-topic: mldn-microboot
  11. producer:
  12. key-serializer: org.apache.kafka.common.serialization.StringSerializer
  13. value-serializer: org.apache.kafka.common.serialization.StringSerializer
  14. properties:
  15. sasl.mechanism: PLAIN
  16. security.protocol: SASL_PLAINTEXT

7、 【microboot-kafka-producer】定义消息发送的服务接口:

  1. package cn.study.microboot.producer;
  2. public interface IMessageProducerService {
  3. public void sendMessage(String msg) ;
  4. }
  5. package cn.study.microboot.service.impl;
  6. import javax.annotation.Resource;
  7. import org.springframework.kafka.core.KafkaTemplate;
  8. import org.springframework.stereotype.Service;
  9. import cn.study.microboot.service.IMessageProducerService;
  10. @Service
  11. public class MessageProducerServiceImpl implements IMessageProducerService {
  12. @Resource
  13. private KafkaTemplate<String, String> kafkaTemplate;
  14. @Override
  15. public void send(String msg) {
  16. this.kafkaTemplate.sendDefault("study-key", msg);
  17. }
  18. }

8、 【microboot-kafka-producer】修改程序启动类:

  1. package cn.mldn.microboot;
  2. import org.springframework.boot.SpringApplication;
  3. import org.springframework.boot.autoconfigure.SpringBootApplication;
  4. @SpringBootApplication // 启动SpringBoot程序,而后自带子包扫描
  5. public class StartSpringBootMain {
  6. static {
  7. System.setProperty("java.security.auth.login.config",
  8. "d:/kafka_client_jaas.conf"); // 表示系统环境属性
  9. }
  10. public static void main(String[] args) throws Exception {
  11. SpringApplication.run(StartSpringBootMain.class, args);
  12. }
  13. }

9、 【microboot-kafka-producer】编写消息发送的程序类:

  1. package cn.study.microboot;
  2. import javax.annotation.Resource;
  3. import org.junit.Test;
  4. import org.junit.runner.RunWith;
  5. import org.springframework.boot.test.context.SpringBootTest;
  6. import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
  7. import org.springframework.test.context.web.WebAppConfiguration;
  8. import cn.study.microboot.service.IMessageProducerService;
  9. @SpringBootTest(classes = StartSpringBootMain.class)
  10. @RunWith(SpringJUnit4ClassRunner.class)
  11. @WebAppConfiguration
  12. public class TestMessageService {
  13. @Resource
  14. private IMessageProducerService messageService;
  15. @Test
  16. public void testStart() throws Exception {
  17. for (int x = 0; x < 100; x++) {
  18. this.messageService.send("study - " + x);
  19. }
  20. }
  21. }

在使用 Kafka 进行数据处理的时候一定要记住,它速度快的主要原因是采用的协议、处理的模式、零拷贝。

3、总结

实际开发之中 90%环境下常用的三个消息组件:ActiveMQ、RabbitMQ、Kafka 的全部定义都在此处,以后你们所从事的开发 里面一定会有消息组件的身影。消息组件带来的最直观好处:数据缓冲,可以保证消息不丢失。

面试题:请解释一下 ActiveMQ 与 RabbitMQ 区别?

· ActiveMQ 使用的是 JMS 协议处理,所以性能比较差,在 ActiveMQ 里面其组成比较简单就是进行主题或者是队列消息的 处理;

·RabbitMQ 使用的是 AMQP 处理,该处理属于一种协议处理,所以处理的性能会比较高,在 RabbitMQ 里面提供有 exchange、 queue、bind 的概念,所有的用户提交的消息发送给 exchange,而后由 bind 绑定 exchange 与 queue,最后根据 routingkey 进行消息 的发送处理,利用这一概念可以实现 fanout(广播)、topic(主题)、direct(直连)的操作处理。同时在 Rabbitmq 之中还通过有虚 拟主机的概念,也就是说不同的虚拟主机可以有自己独立的用户管理、空间管理。

面试题:请解释一下 RabbitMQ 与 Kafka 关系?

· 使用最为广泛性能也比较好的就是 RabbitMQ 组件,Rabbitmq 中的消息消费完就删除,RabbitMQ 本身支持的集群功能有 限,必须结合 HAProxy、Keepalived 才能够实现负载均衡与 HA 技术;

· Kafka 采用零拷贝、批量读取技术可以实现高效的消息交互,Kafka 中的消息会保存两天,同时提供有一个 offset 可以实现 历史消息的读取,Kafka 直接支持有 HA 与负载均衡的支持,在 Kafka 里面支持有数据的副本操作,可以保证数据更加安全。

转载于:https://www.cnblogs.com/leeSmall/p/8721556.html

发表评论

表情:
评论列表 (有 0 条评论,684人围观)

还没有评论,来说两句吧...

相关阅读

    相关 SpringBoot整合kafka

    > 经过前三篇文章 安装jdk 安装zookeeper 以及安装kafka 全部已经竣工了,不知道小伙伴们成功搭建kafka了不。 > 憋了三天的大招,今天放出来吧。今天大家