前言
学习 rabbitMQ 代码
前面学习了 RabbitMQ 基础,现在主要记录下学习 Spring Boot 整合 RabbitMQ ,调用它的 API ,以及中间使用的相关功能的记录。
相关的可以去我的博客/RabbitMQ
正文
我这里测试都是使用的是 topic
交换器,Spring Boot 2.0.0, jdk 1.8
配置
Spring Boot 版本 2.0.0
在 pom.xml
文件中引入 AMQP 的依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
在系统配置文件中加入连接属性
spring:
application:
name: RabbitMQ-Demo
rabbitmq:
host: k.wuwii.com
port: 5672
username: kronchan
password: 123456
#virtual-host: test
publisher-confirms: true # 开启确认消息是否到达交换器,需要设置 true
publisher-returns: true # 开启确认消息是否到达队列,需要设置 true
基本的使用
消费者
新增一个消费者类:
@Log
public class MessageReceiver implements ChannelAwareMessageListener {
@Override
public void onMessage(Message message, Channel channel) throws Exception {
try {
byte[] body = message.getBody();
log.info(">>>>>>> receive: " + new String(body));
} finally {
// 确认成功消费,否则消息会转发给其他的消费者,或者进行重试
channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
}
}
}
配置类
新增 RabbitMQ 的配置类,主要是对消费者的队列,交换器,路由键的一些设置:
@Configuration
public class RabbitMQConfig {
public final static String QUEUE_NAME = "springboot.demo.test1";
public final static String ROUTING_KEY = "route-key";
public final static String EXCHANGES_NAME = "demo-exchanges";
@Bean
public Queue queue() {
// 是否持久化
boolean durable = true;
// 仅创建者可以使用的私有队列,断开后自动删除
boolean exclusive = false;
// 当所有消费客户端连接断开后,是否自动删除队列
boolean autoDelete = false;
return new Queue(QUEUE_NAME, durable, exclusive, autoDelete);
}
/**
* 设置交换器,这里我使用的是 topic exch