因为publisher和consumer服务都需要amqp依赖,因此这里把依赖直接放到父工程mq-demo中
<!--AMQP依赖,包含RabbitMQ-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
spring:
rabbitmq:
host: 192.168.88.129 # rabbitmq所在的虚拟主机ip地址
port: 5672 # 端口
username: yangjian # 用户名
password: 123321 # 密码
virtual-host: / # 虚拟主机
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;
import java.util.HashMap;
import java.util.Map;
/**
* @Author YJ
* @Date 2024/3/23 10:15
* Description:测试 spring amqp
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringAmqpTest {
@Autowired
private RabbitTemplate rabbitTemplate;
@Test
public void testSendMessage2SimpleQueue() {
String queueName = "simple.queue";
String message = "hello, spring amqp!";
rabbitTemplate.convertAndSend(queueName,message);
}
}
spring:
rabbitmq:
host: 192.168.88.129 # rabbitmq所在的虚拟主机ip地址
port: 5672 # 端口
username: yangjian # 用户名
password: 123321 # 密码
virtual-host: / # 虚拟主机
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import java.time.LocalTime;
import java.util.Map;
/**
* @Author YJ
* @Date 2023/3/23 10:35
* Description:接收消息
*/
@Component
public class SpringRabbitListener {
@RabbitListener(queues = "simple.queue")
public void listenSimpleQueue(String msg) {
System.out.println("消费者接收到simple.queue的消息:【" + msg + "】");
}
}
工作队列 可以提高消息处理速度,避免队列消息堆积
@Test
public void testSendMessage2WorkQueue() throws InterruptedException {
String queueName = "simple.queue";
String message = "hello, message__";
for (int i = 1; i <= 50; i++) {
rabbitTemplate.convertAndSend(queueName,message + i);
//每发送一条睡眠20ms
Thread.sleep(20);
}
}
@RabbitListener(queues = "simple.queue")
public void listenWorkQueue1(String msg) throws InterruptedException {
System.out.println("消费者1接收到simple.queue的消息:【" + msg + "】" + LocalTime.now());
Thread.sleep(20);
}
@RabbitListener(queues = "simple.queue")
public void listenWorkQueue2(String msg) throws InterruptedException {
System.err.println("消费者2........接收到simple.queue的消息:【" + msg + "】" + LocalTime.now());
Thread.sleep(200);
}
这里发现发送、接收消息已经远远超出了1秒,而且消费者1处理的都是奇数消息,消费者2处理的都是偶数消息,这是因为这种分配方式没有考虑两个消费者的能力,它是将消息平均分配给两个消费者的,这是源于rabbitmq底层有一个消息预取机制,这个机制是当消息发送到队列中后,队列会对消息进行投递,消费者的channel通道会提前把消息获取到,当消费者处理消息的时间不同时,处理消息快的消费者会提前结束,处理消息慢的消费者所耗费的时间就更久一些,这样就导致总的处理时间超出了。
spring:
rabbitmq:
host: 192.168.88.129 # rabbitmq的ip地址
port: 5672 # 端口
username: yangjian # 用户名
password: 123321 # 密码
virtual-host: / # 虚拟主机
listener:
simple:
prefetch: 1 # 每次只能获取一条消息,处理完成才能获取下一个消息
发布订阅模式与之前案例的区别就是允许将同一消息发送给多个消费者。实现方式是加入了exchange(交换机)。
常见的exchange类型包括:
exchange负责消息路由,而不是存储,路由失败则消息丢失
Fanout Exchange会将接收到的消息路由到每一个跟其绑定的queue
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;
/**
* @Author YJ
* @Date 2024/3/23 13:35
* Description:队列绑定交换机
*/
@Configuration
public class FanoutConfig {
//practice.fanout
@Bean
public FanoutExchange fanoutExchange() {
return new FanoutExchange("practice.fanout");
}
//fanout.queue1
@Bean
public Queue fanoutQueue1() {
return new Queue("fanout.queue1");
}
//绑定队列1到交换机
@Bean
public Binding fanoutBinding1(Queue fanoutQueue1,FanoutExchange fanoutExchange) {
return BindingBuilder
.bind(fanoutQueue1)
.to(fanoutExchange);
}
//fanout.queue2
@Bean
public Queue fanoutQueue2() {
return new Queue("fanout.queue2");
}
//绑定队列2到交换机
@Bean
public Binding fanoutBinding2(Queue fanoutQueue2,FanoutExchange fanoutExchange) {
return BindingBuilder
.bind(fanoutQueue2)
.to(fanoutExchange);
}
}
@RabbitListener(queues = "fanout.queue1")
public void listenFanoutQueue1(String msg) throws InterruptedException {
System.out.println("消费者接收到fanout.queue1的消息:【" + msg + "】");
Thread.sleep(200);
}
@RabbitListener(queues = "fanout.queue2")
public void listenFanoutQueue2(String msg) throws InterruptedException {
System.out.println("消费者接收到fanout.queue2的消息:【" + msg + "】");
Thread.sleep(200);
}
@Test
public void testSendFanoutExchange() {
//交换机名称
String exchange = "practice.fanout";
//消息
String message = "hello everyone!";
//发送消息
rabbitTemplate.convertAndSend(exchange,"",message);
}
Direct Exchange会将接收到的消息根据规则路由到指定的Queue,因此称为路由模式(routes)
- 每一个Queue都与Exchange设置一个BindingKey
- 发布者发送消息时,指定消息的RoutingKey
- Exchange:将消息路由到BindingKey.与消息RoutingKey一致的队列
@RabbitListener(bindings = @QueueBinding(
value = @Queue(name = "direct.queue1"),
exchange = @Exchange(name = "practice.direct",type = ExchangeTypes.DIRECT),
key = {"red","blue"}
))
public void listenDirectQueue1(String msg) {
System.out.println("消费者接收到direct.queue1的消息:【" + msg + "】");
}
@RabbitListener(bindings = @QueueBinding(
value = @Queue(name = "direct.queue2"),
exchange = @Exchange(name = "practice.direct",type = ExchangeTypes.DIRECT),
key = {"red","yellow"}
))
public void listenDirectQueue2(String msg) {
System.out.println("消费者接收到direct.queue2的消息:【" + msg + "】");
}
@Test
public void testSendDirectExchange() {
//交换机名称
String exchange = "practice.direct";
//消息
String message = "hello blue!";
//发送消息
rabbitTemplate.convertAndSend(exchange,"blue",message);
}
TopicExchange.与DirectExchange类似,区别在于routing Key必须是多个单词的列表,并且以 . 分割。
- Queue.与Exchange:指定BindingKey时可以使用通配符
- #:代指0个或多个单词
- *:代指一个单词
@RabbitListener(bindings = @QueueBinding(
value = @Queue(name = "topic.queue1"),
exchange = @Exchange(value = "practice.topic",type = ExchangeTypes.TOPIC),
key = "china.#"
))
public void listenTopicQueue1(String msg) {
System.out.println("消费者接收到topic.queue1的消息:【" + msg + "】");
}
@RabbitListener(bindings = @QueueBinding(
value = @Queue(name = "topic.queue2"),
exchange = @Exchange(value = "practice.topic",type = ExchangeTypes.TOPIC),
key = "#.news"
))
public void listenTopicQueue2(String msg) {
System.out.println("消费者接收到topic.queue2的消息:【" + msg + "】");
}
@Test
public void testSendTopicExchange() {
//交换机名称
String exchange = "practice.topic";
//消息
String message = "天津,晴~";
//发送消息
rabbitTemplate.convertAndSend(exchange,"china.weathers",message);
}
在SpringAMQP的发送方法中,接收消息的类型是Object,也就是说我们可以发送任意对象类型的消息,SpringAMQP会帮我们序列化为字节后发送。
@Bean
public Queue objectQueue() {
return new Queue("object.queue");
}
@Test
public void testSendObjectQueue() {
Map<String,Object> msg = new HashMap<>();
msg.put("name","YJ");
msg.put("age",22);
rabbitTemplate.convertAndSend("object.queue",msg);
}
Spring的对消息对象的处理是由org.springframework.amqp.support.converter.MessageConverter来处理的。而默认实现是SimpleMessageConverter,基于JDK的ObjectOutputStream完成序列化。
如果要修改只需要定义一个MessageConverter类型的Bean即可,推荐用JSON方式序列化,步骤如下
<!--jackson依赖(消息转换器)-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
@Bean
public MessageConverter messageConverter() {
return new Jackson2JsonMessageConverter();
}
<!--jackson依赖(消息转换器)-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
@Bean
public MessageConverter messageConverter() {
return new Jackson2JsonMessageConverter();
}
@RabbitListener(queues = "object.queue")
public void listenObjectQueue(Map<String,Object> msg) {
System.out.println("接收到object.queue的消息:" + msg);
}