什么是SpringAMQP
SpringAmqp的官方地址:Spring AMQP
一、利用SpringAMQP实现HelloWorld中的基础消息队列功能
发送消息
步骤1:引入AMQP依赖
因为publisher和consumer服务都需要amqp依赖,因此这里把依赖直接放到父工程mq-demo中:
org.springframework.boot
spring-boot-starter-amqp
步骤2:
1.在publisher服务中编写application.yml,添加mq连接信息:
spring:
rabbitmq:
host: 112.74.108.223 # 主机名
port: 5672 # 端口
virtual-host: / # 虚拟主机
username: itcast # 用户名
password: 123321 # 密码
2.在publisher服务中新建一个测试类,编写测试方法:
package cn.itcast.mq.helloworld;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringAmqpTest {
@Autowired
private RabbitTemplate rabbitTemplate;
@Test
public void testSimpleQueue() {
String queueName = "simple.queue";
String message = "hello, spring amqp!";
rabbitTemplate.convertAndSend(queueName, message);
}
}
接收消息
1.在consumer服务中编写application.yml,添加mq连接信息:配置同上
2.在consumer服务中新建一个类,编写消费逻辑:
package cn.itcast.mq.listener;
import org.junit.Test;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
@Component
public class SpringRabbitListener {
@RabbitListener(queues = "simple.queue")
public void listenSimpleQueueMessage(String msg) throws InterruptedException {
System.out.println("spring 消费者接收到消息 :【" + msg + "】");
}
}
二、一个发布者,两个消费者时
1.模拟两个消费者,用线程睡眠模拟处理耗时
@RabbitListener(queues = "simple.queue")
public void listenWorkQueueMessage(String msg) throws InterruptedException {
System.out.println("spring 消费者111111111111接收到消息 :【" + msg + "】"+ LocalTime.now());
Thread.sleep(20);
}
@RabbitListener(queues = "simple.queue")
public void listenWorkQueueMessage2(String msg) throws InterruptedException {
System.err.println("spring 消费者222222222接收到消息 :【" + msg + "】"+ LocalTime.now());
Thread.sleep(200);
}
2.模拟发布50条消息
@Test
public void testSimpleQueue2() throws InterruptedException {
String queueName = "simple.queue";
String message = "hello, spring message__";
for(int i = 0;i<50;i++){
rabbitTemplate.convertAndSend(queueName, message+i);
Thread.sleep(20);
}
}
默认消息分配是平均分配,如果消费者处理慢,则影响总效率,在消费者模块加入以下配置则可以控制预取消息的上限
spring:
rabbitmq:
host: 112.74.108.223 # 主机名
port: 5672 # 端口
virtual-host: / # 虚拟主机
username: itcast # 用户名
password: 123321 # 密码
#消费预取限制
listener:
simple:
prefetch: 1 # 每次只能获取一条消息,处理完成才能获取下一个消息
三、交换机
实现步骤
1.在consumer服务中,利用代码声明队列、交换机,并将两者绑定 ,在consumer服务常见一个类,添加@Configuration注解,并声明FanoutExchange、Queue和绑定关系对象Binding,代码如下
package cn.itcast.mq.config;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.FanoutExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
@Configuration
public class FanoutConfig {
// 声明FanoutExchange交换机
@Bean
public FanoutExchange fanoutExchange(){
return new FanoutExchange("itcast.fanout");
}
// 声明第1个队列
@Bean
public Queue fanoutQueue1(){
return new Queue("fanout.queue1");
}
// 绑 定队列1和交换机
@Bean
public Binding bindingQueue1(Queue fanoutQueue1, FanoutExchange fanoutExchange){
return BindingBuilder.bind(fanoutQueue1).to(fanoutExchange);
}
// 声明第2个队列
@Bean
public Queue fanoutQueue2(){
return new Queue("fanout.queue2");
}
// 绑 定队列2和交换机
@Bean
public Binding bindingQueue2(Queue fanoutQueue2, FanoutExchange fanoutExchange2){
return BindingBuilder.bind(fanoutQueue2).to(fanoutExchange2);
}
}
2.定义消息接收
@RabbitListener(queues = "fanout.queue1")
public void listenFanoutQueue1(String msg) throws InterruptedException {
System.out.println("spring 消费者111111111111接收到消息 :【" + msg + "】"+ LocalTime.now());
}
@RabbitListener(queues = "fanout.queue2")
public void listenFanoutQueue2(String msg) throws InterruptedException {
System.out.println("spring 消费者22222222接收到消息 :【" + msg + "】"+ LocalTime.now());
}
3.定义消息发送
@Test
public void testFanout() throws InterruptedException {
//交换机名称
String exchangeName = "itcast.fanout";
//消息
String message = "hello, spring message__";
//发送消息
rabbitTemplate.convertAndSend(exchangeName,"",message);
}
4.指定key发送与接收消息
@Test
public void testFanout() throws InterruptedException {
//交换机名称
String exchangeName = "itcast.direct";
//消息
String message = "hello, spring message__";
//发送消息
rabbitTemplate.convertAndSend(exchangeName,"yellow",message);
}
//消费者1
@RabbitListener(bindings = @QueueBinding(
value=@Queue(name = "direct.queue1"),
exchange = @Exchange(name = "itcast.direct"),
key = {"red","blue"}
))
public void ListenDirectQuery1(String msg){
System.out.println("spring 消费者11接收到消息 :【" + msg + "】"+ LocalTime.now());
}
//消费者2
@RabbitListener(bindings = @QueueBinding(
value=@Queue(name = "direct.queue2"),
exchange = @Exchange(name = "itcast.direct"),
key = {"red","yellow"}
))
public void ListenDirectQuery2(String msg){
System.out.println("spring 消费者22接收到消息 :【" + msg + "】"+ LocalTime.now());
}
四、发布订阅-TopicExchange
演示
@Test
public void testFanout2() throws InterruptedException {
//交换机名称
String exchangeName = "itcast.topic";
//消息
String message = "hello, spring message__";
//发送消息
rabbitTemplate.convertAndSend(exchangeName,"china.news",message);
}
@RabbitListener(bindings = @QueueBinding(
value = @Queue(name = "topic.queue1"),
exchange = @Exchange(name = "itcast.topic",type = ExchangeTypes.TOPIC),
key = "china.#"
))
public void ListenTopicQuery1(String msg){
System.out.println("spring 消费者Topic q1接收到消息 :【" + msg + "】");
}
@RabbitListener(bindings = @QueueBinding(
value = @Queue(name = "topic.queue1"),
exchange = @Exchange(name = "itcast.topic",type = ExchangeTypes.TOPIC),
key = "#.news"
))
public void ListenTopicQuery2(String msg){
System.out.println("spring 消费者Topic q2接收到消息 :【" + msg + "】");
}
五、SpringAMQP-消息转换器
在SpringAMQP的发送方法中,接收消息的类型是Object,也就是说我们可以发送任意对象类型的消息,SpringAMQP会帮我们序列化为字节后发送。
消息转换器
Spring的对消息对象的处理是由org.springframework.amqp.support.converter.MessageConverter来处理的。而默认实现是SimpleMessageConverter,基于JDK的ObjectOutputStream完成序列化。
如果要修改只需要定义一个MessageConverter 类型的Bean即可。推荐用JSON方式序列化,步骤如下:
1. 我们在 publisher 服务引入依赖:com.fasterxml.jackson.core jackson-databind
2.我们在publisher服务声明MessageConverter:
@Bean
public MessageConverter jsonMessageConverter(){
return new Jackson2JsonMessageConverter();
}
3.我们在consumer服务引入Jackson依赖:
com.fasterxml.jackson.core jackson-databind
4.我们在consumer服务定义MessageConverter:
@Bean
public MessageConverter jsonMessageConverter(){
return new Jackson2JsonMessageConverter();
}
5.然后定义一个消费者,监听object.queue队列并消费消息:
@RabbitListener(queues = "object.queue") public void listenObjectQueue(Mapmsg) { System.out.println("收到消息:【" + msg + "】"); }



