在大多应用中,我们系统之间需要进行异步通信,即异步消息,本篇文章主要讲SpringBoot与RabbitMQ整合。
文章目录
- 1. RabbitMQ 快速入门
- 2. Spring 支持
- 3. SpringBoot 整合RabbitMQ
- 3.1 消息的监听
1. RabbitMQ 快速入门
2. Spring 支持
- spring-jms提供了对JMS的支持
- spring-rabbit提供了对AMQP的支持
- 需要ConnectionFactory的实现来连接消息代理
- 提供JmsTemplate、RabbitTemplate类来发送消息
- @JmsListener(JMS)、@RabbitListener(AMQP)注解在方法上监听消息代理发 布的消息
- @EnableJms、@EnableRabbit开启支持
Spring Boot自动配置
- JmsAutoConfiguration
- RabbitAutoConfiguration
3. SpringBoot 整合RabbitMQ
1.导入依赖
dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
2.配置文件
spring.rabbitmq.host=47.94.231.234
#账号密码默认是guest,可以不用配置
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest
#端口号也可以不写,默认是5672
spring.rabbitmq.port=5672
#虚拟主机不配置的话默认是/
spring.rabbitmq.virtual-host=/spring-rabbitmq
3.测试RabbitTemplate
给服务器发送和接收消息
@SpringBootTest
class Springboot10RabbitmqApplicationTests {
@Autowired
RabbitTemplate rabbitTemplate;
@Test
void contextLoads() {
//使用这种方法Message需要自己构造,需要定义Message的消息体内容个消息头
// rabbitTemplate.send(exchange, routingKey, message);
//比较常用的是这个,只需要传入要发送的对象,自动序列化,自动发送给rabbitMq服务器
//rabbitTemplate.convertAndSend(exchange, routingKey, object);
Map<String, Object> map = new HashMap<>();
map.put("msg", "这是第一条消息");
map.put("data","hello world!");
//向exchange.direct交换机中发送一条信息map,根据roottingKey(ewen.direct)到达指定队列
rabbitTemplate.convertAndSend("exchange.direct","ewen.direct",map);
}
}
(在管理页面查看队列收到的消息)
4. 测试接收消息
@Test //接收消息
public void revc() {
Object map = rabbitTemplate.receiveAndConvert("ewen.queue");
System.out.println(map.getClass());
System.out.println(map);
}
5.默认的消息转化器是SimpleMessageConverter,对于对象以jdk序列化方式存储,若要以Json方式存储对象,就要自定义消息转换器
@Configuration
public class MyAMQPConfig {
//自定义MessageConverter,以json的形式发送数据
@Bean
public MessageConverter messageConverter() {
//在容器中导入Json的消息转换器
return new Jackson2JsonMessageConverter();
}
}
-
AmqpAdmin
类管理组件,可用于创建和删除exchange、binding和queue
//创建Direct类型的Exchange
amqpAdmin.declareExchange(new DirectExchange("admin.direct"));
//创建Queue,也可以指定一些参数
amqpAdmin.declareQueue(new Queue("admin.test"));
//将创建的队列与Exchange绑定
amqpAdmin.declareBinding(new Binding("admin.test", Binding.DestinationType.QUEUE,"admin.direct","admin.test",null));
3.1 消息的监听
首先在启动类上开启
在回调方法上标注@RabbitListener
注解,并设置其属性queues,注册监听队列,当该队列收到消息时,标注方法会被调用,可分别使用Message和保存消息所属对象进行消息接收,若使用Object对象进行消息接收,实际上接收到的也是Message。相当于接受消息。
@Service
public class BookService {
@RabbitListener(queues = {"admin.test"})
public void receive1(Book book){
System.out.println("收到消息:"+book);
}
@RabbitListener(queues = {"admin.test"})
public void receive1(Object object){
System.out.println("收到消息:"+object.getClass());
//收到消息:class org.springframework.amqp.core.Message
}
@RabbitListener(queues = {"admin.test"})
public void receive2(Message message){
System.out.println("收到消息"+message.getHeaders()+"---"+message.getPayload());
}
}