RabbitMQ路由键与队列的绑定
需求: 通过死信队列与延时队列定时释放订单
// 订单创建成功,发送到延时队列中
rabbitTemplate.convertAndSend("order-event-exchange","order.create.order",order.getOrder());
// 根据路由键order.create.order,找到绑定的队列是一个延时队列 order.delay.queue
@Bean
public Binding orderCreateBinding() {
/*
* String destination, 目的地(队列名或者交换机名字)
* DestinationType destinationType, 目的地类型(Queue、Exhcange)
* String exchange,
* String routingKey,
* Map<String, Object> arguments
* */
return new Binding("order.delay.queue",
Binding.DestinationType.QUEUE,
"order-event-exchange",
"order.create.order",
null);
}
// x-dead-letter-routing-key,代表延时队列到期后,走 order.release.order 路由键
@Bean
public Queue orderDelayQueue() {
/*
Queue(String name, 队列名字
boolean durable, 是否持久化
boolean exclusive, 是否排他
boolean autoDelete, 是否自动删除
Map<String, Object> arguments) 属性
*/
HashMap<String, Object> arguments = new HashMap<>();
arguments.put("x-dead-letter-exchange", "order-event-exchange");
arguments.put("x-dead-letter-routing-key", "order.release.order");
arguments.put("x-message-ttl", 60000); // 消息过期时间 1分钟
Queue queue = new Queue("order.delay.queue", true, false, false, arguments);
return queue;
}
// 最后就路由到order.release.order.queue队列
@Bean
public Binding orderReleaseBinding() {
return new Binding("order.release.order.queue",
Binding.DestinationType.QUEUE,
"order-event-exchange",
"order.release.order",
null);
}
// 然后就是监听消费消息
package com.xunqi.gulimall.order.listener;
import com.rabbitmq.client.Channel;
import com.xunqi.gulimall.order.entity.OrderEntity;
import com.xunqi.gulimall.order.service.OrderService;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.IOException;
/**
* @Description: 定时关闭订单
* @Created: with IntelliJ IDEA.
* @author: 夏沫止水
* @createTime: 2020-07-07 09:54
**/
@RabbitListener(queues = "order.release.order.queue")
@Service
public class OrderCloseListener {
@Autowired
private OrderService orderService;
@RabbitHandler
public void listener(OrderEntity orderEntity, Channel channel, Message message) throws IOException {
System.out.println("收到过期的订单信息,准备关闭订单" + orderEntity.getOrderSn());
try {
orderService.closeOrder(orderEntity);
channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
} catch (Exception e) {
channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
}
}
}
todo 这其实不能单独成一篇文章,有时间给合并或者删除吧
凡人与圣人的差别就在眼前的那一张纸,凡人投胎转世都带着前世死去时蒙在脸上的蒙脸纸,只有圣人是被天神揭去了那张纸投胎的。
白鹿原
原文地址:https://blog.csdn.net/weixin_44431371/article/details/143389389
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!