在这里插入图片描述
Spring Boot整合RabbitMQ
github地址:
https://github.com/erlieStar/rabbitmq-examples
Spring有三种配置方式
- 基于XML
- 基于JavaConfig
- 基于注解
当然现在已经很少使用XML来做配置了,只介绍一下用JavaConfig和注解的配置方式
RabbitMQ整合Spring Boot,我们只需要增加对应的starter即可
org.springframework.boot spring-boot-starter-amqp
基于注解
在application.yaml的配置如下
spring: rabbitmq: host: myhost port: 5672 username: guest password: guest virtual-host: /log: exchange: log.exchange info: queue: info.log.queue binding-key: info.log.key error: queue: error.log.queue binding-key: error.log.key all: queue: all.log.queue binding-key: '*.log.key'
消费者代码如下
@Slf4j@Componentpublic class LogReceiverListener { /** * 接收info级别的日志 */ @RabbitListener( bindings = @QueueBinding( value = @Queue(value = "${log.info.queue}", durable = "true"), exchange = @Exchange(value = "${log.exchange}", type = ExchangeTypes.TOPIC), key = "${log.info.binding-key}" ) ) public void infoLog(Message message) { String msg = new String(message.getBody()); log.info("infoLogQueue 收到的消息为: {}", msg); } /** * 接收所有的日志 */ @RabbitListener( bindings = @QueueBinding( value = @Queue(value = "${log.all.queue}", durable = "true"), exchange = @Exchange(value = "${log.exchange}", type = ExchangeTypes.TOPIC), key = "${log.all.binding-key}" ) ) public void allLog(Message message) { String msg = new String(message.getBody()); log.info("allLogQueue 收到的消息为: {}", msg); }}
生产者如下
@RunWith(SpringRunner.class)@SpringBootTestpublic class MsgProducerTest { &