当前位置:   article > 正文

RabbitMQ整合SpringCloud_com.rabbiter.em

com.rabbiter.em

RabbitMQ相关知识点思维导图如下:

注意一点,在发送消息的时候对template进行配置mandatory=true保证监听有效;生产端还可以配置其他属性,比如发送重试,超时时间、次数、间隔等

消费端核心配置

  • 首先配置手工确认模式,用于ACK的手工处理,这样我们可以保证消息的可靠性送达,或者在消费端消费失败的时候可以做到重回队列、根据业务记录日志等处理
  • 可以设置消费端的监听个数和最大个数,用于控制消费端的并发情况

@RabbitListener注解的使用

消费端监听@RabbitListener注解,这个对于在实际工作中非常的好用;@RabbitListener是一个组合注解,里面可以注解配置(@QueueBinding、@Queue、@Exchange)直接通过这个组合注解一次性搞定消费端交换机、队列、绑定、路由、并且配置监听功能等

相关代码

  • rabbitmq-common子项目:

 order.java(注意一定要实现序列号接口):

  1. package com.ue.entity;
  2. import java.io.Serializable;
  3. public class Order implements Serializable {
  4. private String id;
  5. private String name;
  6. public Order() {
  7. }
  8. public Order(String id, String name) {
  9. super();
  10. this.id = id;
  11. this.name = name;
  12. }
  13. public String getId() {
  14. return id;
  15. }
  16. public void setId(String id) {
  17. this.id = id;
  18. }
  19. public String getName() {
  20. return name;
  21. }
  22. public void setName(String name) {
  23. this.name = name;
  24. }
  25. }

pom.xml:

  1. <dependencies>
  2. <dependency>
  3. <groupId>org.springframework.boot</groupId>
  4. <artifactId>spring-boot-starter</artifactId>
  5. </dependency>
  6. <dependency>
  7. <groupId>org.projectlombok</groupId>
  8. <artifactId>lombok</artifactId>
  9. <optional>true</optional>
  10. </dependency>
  11. <dependency>
  12. <groupId>org.springframework.boot</groupId>
  13. <artifactId>spring-boot-starter-test</artifactId>
  14. <scope>test</scope>
  15. <exclusions>
  16. <exclusion>
  17. <groupId>org.junit.vintage</groupId>
  18. <artifactId>junit-vintage-engine</artifactId>
  19. </exclusion>
  20. </exclusions>
  21. </dependency>
  22. </dependencies>
  • rabbitmq-springcloud-consumer子项目:

RabbitReceiver.java(消费端,实际开发中可当成是service层,在controller层调用): 

  1. package com.ue.conusmer;
  2. import com.rabbitmq.client.Channel;
  3. import com.ue.entity.Order;
  4. import org.springframework.amqp.rabbit.annotation.*;
  5. import org.springframework.amqp.support.AmqpHeaders;
  6. import org.springframework.messaging.Message;
  7. import org.springframework.messaging.handler.annotation.Headers;
  8. import org.springframework.messaging.handler.annotation.Payload;
  9. import org.springframework.stereotype.Component;
  10. import java.util.Map;
  11. @Component
  12. public class RabbitReceiver {
  13. @RabbitListener(bindings = @QueueBinding(
  14. value = @Queue(value = "queue-1",//指定消息队列名称
  15. durable="true"),
  16. exchange = @Exchange(value = "exchange-1",//指定交换机名称
  17. durable="true",
  18. type= "topic", //指定交换机的类型:主题交换机
  19. ignoreDeclarationExceptions = "true"),
  20. key = "springboot.*"//指定路由key
  21. )
  22. )
  23. @RabbitHandler
  24. public void onMessage(Message message, Channel channel) throws Exception {
  25. System.err.println("--------------------------------------");
  26. System.err.println("消费端Payload: " + message.getPayload());
  27. Long deliveryTag = (Long)message.getHeaders().get(AmqpHeaders.DELIVERY_TAG);
  28. //手工ACK
  29. channel.basicAck(deliveryTag, false);
  30. }
  31. /**
  32. * spring.rabbitmq.listener.order.queue.name=queue-2
  33. spring.rabbitmq.listener.order.queue.durable=true
  34. spring.rabbitmq.listener.order.exchange.name=exchange-1
  35. spring.rabbitmq.listener.order.exchange.durable=true
  36. spring.rabbitmq.listener.order.exchange.type=topic
  37. spring.rabbitmq.listener.order.exchange.ignoreDeclarationExceptions=true
  38. spring.rabbitmq.listener.order.key=springboot.*
  39. * @param order
  40. * @param channel
  41. * @param headers
  42. * @throws Exception
  43. */
  44. @RabbitListener(bindings = @QueueBinding(
  45. value = @Queue(value = "${spring.rabbitmq.listener.order.queue.name}",
  46. durable="${spring.rabbitmq.listener.order.queue.durable}"),
  47. exchange = @Exchange(value = "${spring.rabbitmq.listener.order.exchange.name}",
  48. durable="${spring.rabbitmq.listener.order.exchange.durable}",
  49. type= "${spring.rabbitmq.listener.order.exchange.type}",
  50. ignoreDeclarationExceptions = "${spring.rabbitmq.listener.order.exchange.ignoreDeclarationExceptions}"),
  51. key = "${spring.rabbitmq.listener.order.key}"
  52. )
  53. )
  54. @RabbitHandler
  55. public void onOrderMessage(@Payload Order order,
  56. Channel channel,
  57. @Headers Map<String, Object> headers) throws Exception {
  58. System.err.println("--------------------------------------");
  59. System.err.println("消费端order: " + order.getId());
  60. Long deliveryTag = (Long)headers.get(AmqpHeaders.DELIVERY_TAG);
  61. //手工ACK
  62. channel.basicAck(deliveryTag, false);
  63. }
  64. }

pom.xml:

  1. <dependencies>
  2. <dependency>
  3. <groupId>org.springframework.boot</groupId>
  4. <artifactId>spring-boot-starter</artifactId>
  5. </dependency>
  6. <dependency>
  7. <groupId>com.ue</groupId>
  8. <artifactId>rabbitmq-common</artifactId>
  9. <version>0.0.1-SNAPSHOT</version>
  10. </dependency>
  11. <dependency>
  12. <groupId>org.springframework.boot</groupId>
  13. <artifactId>spring-boot-starter-test</artifactId>
  14. <scope>test</scope>
  15. <exclusions>
  16. <exclusion>
  17. <groupId>org.junit.vintage</groupId>
  18. <artifactId>junit-vintage-engine</artifactId>
  19. </exclusion>
  20. </exclusions>
  21. </dependency>
  22. <dependency>
  23. <groupId>org.springframework.boot</groupId>
  24. <artifactId>spring-boot-starter-amqp</artifactId>
  25. </dependency>
  26. <dependency>
  27. <groupId>junit</groupId>
  28. <artifactId>junit</artifactId>
  29. <version>4.12</version>
  30. <scope>test</scope>
  31. </dependency>
  32. </dependencies>

application.properties:

  1. spring.rabbitmq.addresses=xxx:5672
  2. spring.rabbitmq.username=guest
  3. spring.rabbitmq.password=guest
  4. spring.rabbitmq.virtual-host=/
  5. spring.rabbitmq.connection-timeout=15000
  6. spring.rabbitmq.listener.simple.acknowledge-mode=manual
  7. spring.rabbitmq.listener.simple.concurrency=5
  8. spring.rabbitmq.listener.simple.max-concurrency=10
  9. spring.rabbitmq.listener.order.queue.name=queue-2
  10. spring.rabbitmq.listener.order.queue.durable=true
  11. spring.rabbitmq.listener.order.exchange.name=exchange-2
  12. spring.rabbitmq.listener.order.exchange.durable=true
  13. spring.rabbitmq.listener.order.exchange.type=topic
  14. spring.rabbitmq.listener.order.exchange.ignoreDeclarationExceptions=true
  15. spring.rabbitmq.listener.order.key=springboot.*

MainConfig.java:

  1. package com.ue;
  2. import org.springframework.context.annotation.ComponentScan;
  3. import org.springframework.context.annotation.Configuration;
  4. @Configuration
  5. @ComponentScan({"com.ue.*"})
  6. public class MainConfig {
  7. }
  • rabbitmq-springcloud-producer子项目:

 RabbitSender.java(生产端,实际开发中可当成是service层,在controller层调用):

  1. package com.ue.producer;
  2. import com.ue.entity.Order;
  3. import org.springframework.amqp.rabbit.connection.CorrelationData;
  4. import org.springframework.amqp.rabbit.core.RabbitTemplate;
  5. import org.springframework.amqp.rabbit.core.RabbitTemplate.ConfirmCallback;
  6. import org.springframework.amqp.rabbit.core.RabbitTemplate.ReturnCallback;
  7. import org.springframework.beans.factory.annotation.Autowired;
  8. import org.springframework.messaging.Message;
  9. import org.springframework.messaging.MessageHeaders;
  10. import org.springframework.messaging.support.MessageBuilder;
  11. import org.springframework.stereotype.Component;
  12. import java.util.Map;
  13. @Component
  14. public class RabbitSender {
  15. //自动注入RabbitTemplate模板类
  16. @Autowired
  17. private RabbitTemplate rabbitTemplate;
  18. //回调函数: confirm确认,对于broker来说如果没有被签收或签收,都会给生产端发消息
  19. final ConfirmCallback confirmCallback = new ConfirmCallback() {
  20. @Override
  21. public void confirm(CorrelationData correlationData, boolean ack, String cause) {
  22. System.err.println("correlationData: " + correlationData);
  23. System.err.println("ack: " + ack);
  24. if(!ack){
  25. System.err.println("异常处理....");
  26. }
  27. }
  28. };
  29. //回调函数: return返回,路由键没有找到会进行下面的逻辑处理
  30. final ReturnCallback returnCallback = new ReturnCallback() {
  31. @Override
  32. public void returnedMessage(org.springframework.amqp.core.Message message, int replyCode, String replyText,
  33. String exchange, String routingKey) {
  34. System.err.println("return exchange: " + exchange + ", routingKey: "
  35. + routingKey + ", replyCode: " + replyCode + ", replyText: " + replyText);
  36. }
  37. };
  38. //发送消息方法调用: 构建Message消息
  39. public void send(Object message, Map<String, Object> properties) throws Exception {
  40. MessageHeaders mhs = new MessageHeaders(properties);
  41. Message msg = MessageBuilder.createMessage(message, mhs);
  42. rabbitTemplate.setConfirmCallback(confirmCallback);
  43. rabbitTemplate.setReturnCallback(returnCallback);
  44. //id + 时间戳 全局唯一
  45. CorrelationData correlationData = new CorrelationData("1234567890");
  46. rabbitTemplate.convertAndSend("exchange-1", "springboot.abc", msg, correlationData);
  47. }
  48. //发送消息方法调用: 构建自定义对象消息
  49. public void sendOrder(Order order) throws Exception {
  50. rabbitTemplate.setConfirmCallback(confirmCallback);
  51. rabbitTemplate.setReturnCallback(returnCallback);
  52. //id + 时间戳 全局唯一
  53. CorrelationData correlationData = new CorrelationData("0987654321");
  54. rabbitTemplate.convertAndSend("exchange-2", "springboot.def", order, correlationData);
  55. }
  56. }

pom.xml:

  1. <dependencies>
  2. <dependency>
  3. <groupId>org.springframework.boot</groupId>
  4. <artifactId>spring-boot-starter</artifactId>
  5. </dependency>
  6. <dependency>
  7. <groupId>org.springframework.boot</groupId>
  8. <artifactId>spring-boot-starter-test</artifactId>
  9. <scope>test</scope>
  10. <exclusions>
  11. <exclusion>
  12. <groupId>org.junit.vintage</groupId>
  13. <artifactId>junit-vintage-engine</artifactId>
  14. </exclusion>
  15. </exclusions>
  16. </dependency>
  17. <dependency>
  18. <groupId>com.ue</groupId>
  19. <artifactId>rabbitmq-common</artifactId>
  20. <version>0.0.1-SNAPSHOT</version>
  21. </dependency>
  22. <dependency>
  23. <groupId>org.springframework.boot</groupId>
  24. <artifactId>spring-boot-starter-amqp</artifactId>
  25. </dependency>
  26. <dependency>
  27. <groupId>junit</groupId>
  28. <artifactId>junit</artifactId>
  29. <version>4.12</version>
  30. <scope>test</scope>
  31. </dependency>
  32. </dependencies>

application.properties:

  1. spring.rabbitmq.addresses=xxx:5672
  2. spring.rabbitmq.username=guest
  3. spring.rabbitmq.password=guest
  4. spring.rabbitmq.virtual-host=/
  5. spring.rabbitmq.connection-timeout=15000
  6. spring.rabbitmq.publisher-confirms=true
  7. spring.rabbitmq.publisher-returns=true
  8. spring.rabbitmq.template.mandatory=true

MainConfig.java:

  1. package com.ue;
  2. import org.springframework.context.annotation.ComponentScan;
  3. import org.springframework.context.annotation.Configuration;
  4. @Configuration
  5. @ComponentScan({"com.ue.*"})
  6. public class MainConfig {
  7. }

RabbitmqSpringcloudProducerApplicationTests.java(测试类): 

  1. package com.ue;
  2. import com.ue.entity.Order;
  3. import com.ue.producer.RabbitSender;
  4. import org.junit.Test;
  5. import org.junit.runner.RunWith;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.boot.test.context.SpringBootTest;
  8. import org.springframework.test.context.junit4.SpringRunner;
  9. import java.text.SimpleDateFormat;
  10. import java.util.Date;
  11. import java.util.HashMap;
  12. import java.util.Map;
  13. @RunWith(SpringRunner.class)
  14. @SpringBootTest
  15. public class RabbitmqSpringcloudProducerApplicationTests {
  16. @Autowired
  17. private RabbitSender rabbitSender;
  18. private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
  19. @Test
  20. public void testSender1() throws Exception {
  21. Map<String, Object> properties = new HashMap<>();
  22. properties.put("number", "12345");
  23. properties.put("send_time", simpleDateFormat.format(new Date()));
  24. rabbitSender.send("Hello RabbitMQ For Spring Boot!", properties);
  25. }
  26. @Test
  27. public void testSender2() throws Exception {
  28. Order order = new Order("001", "第一个订单");
  29. rabbitSender.sendOrder(order);
  30. }
  31. }

测试时先启动消费者,再运行测试的方法:

本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号