一、概述
RabbitMQ是由Rabbit公司基于Erlang语言开发的,支持多协议的、性能优秀的消息队列产品。一般消息队列,俗称消息中间件。
主流的消息中间件如下:
二、SpringAMQP介绍
SpringAMQP是SpringBoot整合RabbitMQ的模板,实际上就是一个起步依赖。它有五种模式分别是Simple、WorkQueue、Fanout、Direct、 Topic。
1.Simple(单发)
配置文件:
spring:
rabbitmq:
host: # 主机名
port:# 端口
virtual-host: / # 虚拟主机
username: # 用户名
password: # 密码
2.WorkQueue(单发)
配置文件:
spring:
rabbitmq:
listener:
simple:
prefetch: 1 # 每次只能获取一条消息,处理完成才能获取下一个消息
3.Fanout(群发)
通过交换机,把消息路由到队列,实现群发
4.Direct
通过交换机,通过路由key的精确名称把消息路由到队列,实现群发
发送消息:
@Test
public void directTest(){
rabbitTemplate.convertAndSend("itcast.direct","red","this red");
rabbitTemplate.convertAndSend("itcast.direct","yellow","this yellow");
rabbitTemplate.convertAndSend("itcast.direct","blue","this blue");
}
收到消息
// 创建队列1、声明交换机、绑定队列1和交换机
@RabbitListener(bindings = @QueueBinding(
value = @Queue(name="direct.queue1"),
exchange = @Exchange(name="itcast.direct"),
key = {"blue","red"}
))
public void directQueue1(String message){
System.out.println("directQueue1:"+message);
}
// 创建队列2、声明交换机、绑定队列2和交换机
@RabbitListener(bindings = @QueueBinding(
value = @Queue(name="direct.queue2"),
exchange = @Exchange(name="itcast.direct"),
key = {"yellow","red"}
))
public void directQueue2(String message){
System.out.println("directQueue2:"+message);
}
5.Topic(群发)
通过交换机,通过路由key的部分名称把消息路由到队列,实现群发
发送消息
@Test
public void topicTest(){
rabbitTemplate.convertAndSend("itcast.topic","china.big","china.big");
rabbitTemplate.convertAndSend("itcast.topic","china.big.news","china.big.news");
rabbitTemplate.convertAndSend("itcast.topic","usa.news","usa.news");
}
收到消息
@RabbitListener(bindings = @QueueBinding(
value = @Queue(name="topic.queue1"),
exchange = @Exchange(name="itcast.topic",type = ExchangeTypes.TOPIC),
key = {"china.#"}
))
public void topicQueue1(String message){
System.out.println("topicQueue1:"+message);
}
@RabbitListener(bindings = @QueueBinding(
value = @Queue(name="topic.queue2"),
exchange = @Exchange(name="itcast.topic",type = ExchangeTypes.TOPIC),
key = {"#.news"}
))
public void topicQueue2(String message){
System.out.println("topicQueue2:"+message);
}
(注意)可以使用JSON转换器,解决消息格式问题
导入依赖
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
<version>2.9.5</version>
</dependency>
配置bean
@Bean
public MessageConverter jsonMessageConverter(){
return new Jackson2JsonMessageConverter();
}