SpringBoot整合RabbitMQ及多模式简单实现
本文摘录自:
https://blog.csdn.net/weixin_38305440/article/details/104807062
依赖:
starter添加依赖:
Spring for RabbitMQ
配置文件:
application.yml
spring:
rabbitmq:
host: 192.168.64.140
username: admin
password: admin
简单模式
Bean
@SpringBootApplication
public class Main {
public static void main(String[] args) {
SpringApplication.run(Main.class, args);
}
@Bean
public Queue task_queue() {
/*
* 可用以下形式:
* new Queue("helloworld") - 持久,非排他,非自动删除
* new Queue("helloworld",false,false,false,null)
*/
return new Queue("helloworld",false);
}
}
生产者
AmqpTemplate是rabbitmq客户端API的一个封装工具,提供了简便的方法来执行消息操作.
AmqpTemplate由自动配置类自动创建
@Component
public class SimpleSender {
@Autowired
AmqpTemplate t;
public void send() {
// 这里向 helloworld 队列发送消息
t.convertAndSend("helloworld", "Hello world!! "+System.currentTimeMillis());
System.out.println("消息已发送");
}
}
消费者
通过@RabbitListener
从指定的队列接收消息
使用@RebbitHandler
注解的方法来处理消息
@Component
@RabbitListener(queues = "helloworld")
public class SimpleReceiver {
@RabbitHandler
public void receive(String msg) {
System.out.println("收到: "+msg);
}
}
@RabbitListener注解可以直接加在方法上,这样@RabbitHandler就可以不加了
同时也可以在@RabbitListener上定义队列属性:
@RabbitListener(queuesToDeclare = @Queue(name = "helloworld",durable = "false"))
工作模式
在主程序中创建名为task_queue
的持久队列
@SpringBootApplication
public class Main {
public static void main(String[] args) {
SpringApplication.run(Main.class, args);
}
@Bean
public Queue task_queue() {
// 这个构造方法创建的队列参数为: 持久,非排他,非自动删除
return new Queue("task_queue");
}
}
生产者
@Component
public class WorkSender {
@Autowired
AmqpTemplate t;
public void send() {
while (true) {
System.out.print("输入:");
String s = new Scanner(System.in).nextLine();
//spring 默认将消息的 DeliveryMode 设置为 PERSISTENT 持久化,
t.convertAndSend("task_queue", s);
}
}
}
SpringBoot默认消息是持久化消息,如果需要非持久消息,还需要用MessagePostProcessor进行配置:
//如果需要设置消息为非持久化,可以取得消息的属性对象,修改它的deliveryMode属性
t.convertAndSend("task_queue", (Object) s, new MessagePostProcessor() {
@Override
public Message postProcessMessage(Message message) throws AmqpException {
MessageProperties props = message.getMessageProperties();
props.setDeliveryMode(MessageDeliveryMode.NON_PERSISTENT);
return message;
}
});
消费者
@Component
public class WorkReceiver1 {
@RabbitListener(queues="task_queue")
public void receive1(String s) throws Exception {
System.out.println("receiver1 - 收到: "+s);
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '.') {
Thread.sleep(1000);
}
}
}
@RabbitListener(queues="task_queue")
public void receive2(String s) throws Exception {
System.out.println("receiver2 - 收到: "+s);
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '.') {
Thread.sleep(1000);
}
}
}
}
ACK设置
SpringBoot封装了3个模式:
NONE:不做任何操作,rabbitmq发送消息即删除,不管处理结果如何
AUTO(默认):在方法处理完成后,SpringBoot会自动发送回执
MANUAL:需要手写回执
spring:
rabbitmq:
listener:
simple:
# acknowledgeMode: NONE # rabbitmq的自动确认
acknowledgeMode: AUTO # rabbitmq的手动确认, springboot会自动发送确认回执 (默认)
# acknowledgeMode: MANUAL # rabbitmq的手动确认, springboot不发送回执, 必须自己编码发送回执
MANUAL模式的手动执行确认操作:
@RabbitListener(queues="task_queue")
public void receive1(String s, Channel c, @Header(name=AmqpHeaders.DELIVERY_TAG) long tag) throws Exception {
System.out.println("receiver1 - 收到: "+s);
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '.') {
Thread.sleep(1000);
}
}
// 手动发送确认回执
c.basicAck(tag, false);
}
消息抓取数量
在工作模式中,为了合理分发消息,避免阻塞,需要把qos设置为1
spring:
rabbitmq:
listener:
simple:
prefetch: 1 # qos=1, 默认250
发布和订阅模式
@SpringBootApplication
public class Main {
public static void main(String[] args) {
SpringApplication.run(Main.class, args);
}
@Bean
public FanoutExchange fanoutExchange() {
return new FanoutExchange("logs");
}
}
生产者
生产者向指定的交换机 logs
发送数据.
不需要指定队列名或路由键, 即使指定也无效, 因为 fanout
交换机会向所有绑定的队列发送数据, 而不是有选择的发送.
@Component
public class Publisher {
@Autowired
AmqpTemplate t;
public void send() {
while (true) {
System.out.print("输入:");
String s = new Scanner(System.in).nextLine();
// 指定向 logs 交换机发送, 不指定队列名或路由键
t.convertAndSend("logs","",s);
}
}
}
消费者
消费者需要执行以下操作:
- 定义随机队列(随机命名,非持久,排他,自动删除)
- 定义交换机(可以省略, 已在主程序中定义)
- 将队列绑定到交换机
spring boot 通过注解完成以上操作:
@RabbitListener(bindings = @QueueBinding( //这里进行绑定设置
value = @Queue, //这里定义随机队列,默认属性: 随机命名,非持久,排他,自动删除
exchange = @Exchange(name = "logs", declare = "false") //指定 logs 交换机,因为主程序中已经定义,这里不进行定义
))
@Component
public class Subscriber {
@RabbitListener(bindings = @QueueBinding(value = @Queue, exchange = @Exchange(name = "logs", declare = "false")))
public void receive1(String s) throws Exception {
System.out.println("receiver1 - 收到: "+s);
}
@RabbitListener(bindings = @QueueBinding(value = @Queue, exchange = @Exchange(name = "logs", declare = "false")))
public void receive2(String s) throws Exception {
System.out.println("receiver2 - 收到: "+s);
}
}
路由模式
与发布和订阅模式代码类似, 只是做以下三点调整:
- 使用
direct
交换机 - 队列和交换机绑定时, 设置绑定键
- 发送消息时, 指定路由键
@SpringBootApplication
public class Main {
public static void main(String[] args) {
SpringApplication.run(Main.class, args);
}
@Bean
public DirectExchange fanoutExchange() {
return new DirectExchange("direct_logs");
}
}
生产者
@Component
public class RouteSender {
@Autowired
AmqpTemplate t;
public void send() {
while (true) {
System.out.print("输入消息:");
String s = new Scanner(System.in).nextLine();
System.out.print("输入路由键:");
String key = new Scanner(System.in).nextLine();
// 第二个参数指定路由键
t.convertAndSend("direct_logs",key,s);
}
}
}
消费者
@Component
public class RouteReceiver {
@RabbitListener(bindings = @QueueBinding(value = @Queue,exchange = @Exchange(name = "direct_logs", declare = "false"),key = {"error"}))
public void receive1(String s) throws Exception {
System.out.println("receiver1 - 收到: "+s);
}
@RabbitListener(bindings = @QueueBinding(value = @Queue, exchange = @Exchange(name = "direct_logs", declare = "false"),key = {"error","info","warning"}))
public void receive2(String s) throws Exception {
System.out.println("receiver2 - 收到: "+s);
}
}
主题模式
@SpringBootApplication
public class Main {
public static void main(String[] args) {
SpringApplication.run(Main.class, args);
}
@Bean
public TopicExchange fanoutExchange() {
return new TopicExchange("topic_logs");
}
}
生产者
@Component
public class TopicSender {
@Autowired
AmqpTemplate t;
public void send() {
while (true) {
System.out.print("输入消息:");
String s = new Scanner(System.in).nextLine();
System.out.print("输入路由键:");
String key = new Scanner(System.in).nextLine();
t.convertAndSend("topic_logs",key,s);
}
}
}
消费者
@Component
public class TopicReceiver {
@RabbitListener(bindings = @QueueBinding(value = @Queue,exchange = @Exchange(name = "topic_logs", declare = "false"),key = {"*.orange.*"}))
public void receive1(String s) throws Exception {
System.out.println("receiver1 - 收到: "+s);
}
@RabbitListener(bindings = @QueueBinding(value = @Queue, exchange = @Exchange(name = "topic_logs", declare = "false"),key = {"*.*.rabbit","lazy.#"}))
public void receive2(String s) throws Exception {
System.out.println("receiver2 - 收到: "+s);
}
}
RPC异步调用
@SpringBootApplication
public class Main {
public static void main(String[] args) {
SpringApplication.run(Main.class, args);
}
@Bean
public Queue sendQueue() {
return new Queue("rpc_queue",false);
}
@Bean
public Queue rndQueue() {
return new Queue(UUID.randomUUID().toString(), false);
}
}
服务端
从rpc_queue接收调用数据, 执行运算求斐波那契数,并返回计算结果.
@Rabbitlistener注解对于具有返回值的方法:
- 会自动获取 replyTo 属性
- 自动获取 correlationId 属性
- 向 replyTo 属性指定的队列发送计算结果, 并携带 correlationId 属性
@Component
public class RpcServer {
@RabbitListener(queues = "rpc_queue")
public long getFbnq(int n) {
return f(n);
}
private long f(int n) {
if (n==1 || n==2) {
return 1;
}
return f(n-1) + f(n-2);
}
}
客户端
使用 SPEL 表达式获取随机队列名: "#{rndQueue.name}"
发送调用数据时, 携带随机队列名和correlationId
从随机队列接收调用结果, 并获取correlationId
@Component
public class RpcClient {
@Autowired
AmqpTemplate t;
@Value("#{rndQueue.name}")
String rndQueue;
public void send(int n) {
// 发送调用信息时, 通过前置消息处理器, 对消息属性进行设置, 添加返回队列名和关联id
t.convertAndSend("rpc_queue", (Object)n, new MessagePostProcessor() {
@Override
public Message postProcessMessage(Message message) throws AmqpException {
MessageProperties p = message.getMessageProperties();
p.setReplyTo(rndQueue);
p.setCorrelationId(UUID.randomUUID().toString());
return message;
}
});
}
//从随机队列接收计算结果
@RabbitListener(queues = "#{rndQueue.name}")
public void receive(long r, @Header(name=AmqpHeaders.CORRELATION_ID) String correlationId) {
System.out.println("\n\n"+correlationId+" - 收到: "+r);
}
}