简单实现版
RabbitMq创建队列绑定交换机_rabbitmq 绑定交换机-CSDN博客
@Configuration
public class RabbitmqConfig {
@Value("${rabbitmq.exchange}")
private String exchange;
@Value("${rabbitmq.host}")
private String host;
@Value("${rabbitmq.port}")
private Integer port;
@Value("${rabbitmq.username}")
private String username;
@Value("${rabbitmq.password}")
private String password;
@Value("${rabbitmq.virtual-host}")
private String virtualHost;
@Value("${rabbitmq.queue}")
private String queue;
@Bean
public TopicExchange exchange() {
return new TopicExchange(exchange);
}
@Bean
public ConnectionFactory connectionFactory() {
CachingConnectionFactory connectionFactory = new CachingConnectionFactory(host);
connectionFactory.setUsername(username);
connectionFactory.setPassword(password);
connectionFactory.setPort(port);
connectionFactory.setVirtualHost(virtualHost);
return connectionFactory;
}
@Bean
public AmqpAdmin amqpAdmin() {
return new RabbitAdmin(connectionFactory());
}
@Bean
public RabbitTemplate rabbitTemplate() {
return new RabbitTemplate(connectionFactory());
}
@Bean
public Queue delayedQueue(){
return new Queue(queue);
}
@Bean
public Binding queueBindingExchange(@Qualifier("delayedQueue") Queue queue,
@Qualifier("exchange") Exchange exchange){
return BindingBuilder.bind(queue).to(exchange).with("#").noargs();
}
}
进阶实现版
使用枚举类说明消息队列的所有信息,替代使用配置文件+@Value的形式
/**
* 消息队列枚举配置
* Created by macro on 2018/9/14.
*/
@Getter
public enum QueueEnum {
/**
* 消息通知队列
*/
QUEUE_ORDER_CANCEL("mall.order.direct", "mall.order.cancel", "mall.order.cancel"),
/**
* 消息通知ttl队列
*/
QUEUE_TTL_ORDER_CANCEL("mall.order.direct.ttl", "mall.order.cancel.ttl", "mall.order.cancel.ttl");
/**
* 交换名称
*/
private String exchange;
/**
* 队列名称
*/
private String name;
/**
* 路由键
*/
private String routeKey;
QueueEnum(String exchange, String name, String routeKey) {
this.exchange = exchange;
this.name = name;
this.routeKey = routeKey;
}
}
RabbitMq配置类:使用Builder链式形式声明,可读性更强
/**
* 消息队列配置
* Created by macro on 2018/9/14.
*/
@Configuration
public class RabbitMqConfig {
/**
* 订单消息实际消费队列所绑定的交换机
*/
@Bean
DirectExchange orderDirect() {
return (DirectExchange) ExchangeBuilder
.directExchange(QueueEnum.QUEUE_ORDER_CANCEL.getExchange())
.durable(true)
.build();
}
/**
* 订单延迟队列所绑定的交换机
*/
@Bean
DirectExchange orderTtlDirect() {
return (DirectExchange) ExchangeBuilder
.directExchange(QueueEnum.QUEUE_TTL_ORDER_CANCEL.getExchange())
.durable(true)
.build();
}
/**
* 订单实际消费队列
*/
@Bean
public Queue orderQueue() {
return new Queue(QueueEnum.QUEUE_ORDER_CANCEL.getName());
}
/**
* 订单延迟队列(死信队列)
*/
@Bean
public Queue orderTtlQueue() {
return QueueBuilder
.durable(QueueEnum.QUEUE_TTL_ORDER_CANCEL.getName())
.withArgument("x-dead-letter-exchange", QueueEnum.QUEUE_ORDER_CANCEL.getExchange())//到期后转发的交换机
.withArgument("x-dead-letter-routing-key", QueueEnum.QUEUE_ORDER_CANCEL.getRouteKey())//到期后转发的路由键
.build();
}
/**
* 将订单队列绑定到交换机
*/
@Bean
Binding orderBinding(DirectExchange orderDirect,Queue orderQueue){
return BindingBuilder
.bind(orderQueue)
.to(orderDirect)
.with(QueueEnum.QUEUE_ORDER_CANCEL.getRouteKey());
}
/**
* 将订单延迟队列绑定到交换机
*/
@Bean
Binding orderTtlBinding(DirectExchange orderTtlDirect,Queue orderTtlQueue){
return BindingBuilder
.bind(orderTtlQueue)
.to(orderTtlDirect)
.with(QueueEnum.QUEUE_TTL_ORDER_CANCEL.getRouteKey());
}
}
实践使用
业务场景
用户挑选物品至购物车,结算购物车商品生成订单信息,用户需要在指定时间内完成订单的付款,如果超时未付款应该取消订单。
- 用户进行下单操作(会有锁定商品库存、使用优惠券、积分一系列的操作);
- 生成订单,获取订单的id;
- 获取到设置的订单超时时间(假设设置的为60分钟不支付取消订单);
- 按订单超时时间发送一个延迟消息给RabbitMQ,让它在订单超时后触发取消订单的操作;
- 如果用户没有支付,进行取消订单操作(释放锁定商品库存、返还优惠券、返回积分一系列操作)。
上面的业务场景可以使用延迟队列来处理,当生成订单的同时开启一个延迟消息(携带当前orderId),其中需要设置一个监视器不断监听支付事件,如果达到指定时间订单超时未付款,则开始消费延迟队列的消息(消息到期),执行取消订单的操作。
整合依赖及配置
- 在
pom.xml
中添加AMQP相关依赖;
<!--Spring AMQP相关依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
- 修改
application.yml
文件,在spring节点下添加RabbitMQ相关配置。
spring:
rabbitmq:
host: localhost
port: 5672
virtual-host: /mall
username: mall
password: mall
publisher-returns: true #消息发送到队列确认
publisher-confirm-type: simple #消息发送到交换器确认
实现延迟消息
- 添加消息队列的枚举配置类QueueEnum,用于延迟消息队列及处理取消订单消息队列的常量定义,包括交换机名称、队列名称、路由键名称;
/**
* @auther macrozheng
* @description 消息队列枚举配置
* @date 2018/9/14
* @github https://github.com/macrozheng
*/
@Getter
public enum QueueEnum {
/**
* 消息通知队列
*/
QUEUE_ORDER_CANCEL("mall.order.direct", "mall.order.cancel", "mall.order.cancel"),
/**
* 消息通知ttl队列
*/
QUEUE_TTL_ORDER_CANCEL("mall.order.direct.ttl", "mall.order.cancel.ttl", "mall.order.cancel.ttl");
/**
* 交换机名称
*/
private String exchange;
/**
* 队列名称
*/
private String name;
/**
* 路由键
*/
private String routeKey;
QueueEnum(String exchange, String name, String routeKey) {
this.exchange = exchange;
this.name = name;
this.routeKey = routeKey;
}
}
- 添加RabbitMQ的Java配置,用于配置交换机、队列及队列与交换机的绑定关系;
/**
* @auther macrozheng
* @description 消息队列配置
* @date 2018/9/14
* @github https://github.com/macrozheng
*/
@Configuration
public class RabbitMqConfig {
/**
* 订单消息实际消费队列所绑定的交换机
*/
@Bean
DirectExchange orderDirect() {
return ExchangeBuilder
.directExchange(QueueEnum.QUEUE_ORDER_CANCEL.getExchange())
.durable(true)
.build();
}
/**
* 订单延迟队列所绑定的交换机
*/
@Bean
DirectExchange orderTtlDirect() {
return ExchangeBuilder
.directExchange(QueueEnum.QUEUE_TTL_ORDER_CANCEL.getExchange())
.durable(true)
.build();
}
/**
* 订单实际消费队列
*/
@Bean
public Queue orderQueue() {
return new Queue(QueueEnum.QUEUE_ORDER_CANCEL.getName());
}
/**
* 订单延迟队列(死信队列)
*/
@Bean
public Queue orderTtlQueue() {
return QueueBuilder
.durable(QueueEnum.QUEUE_TTL_ORDER_CANCEL.getName())
.withArgument("x-dead-letter-exchange", QueueEnum.QUEUE_ORDER_CANCEL.getExchange())//到期后转发的交换机
.withArgument("x-dead-letter-routing-key", QueueEnum.QUEUE_ORDER_CANCEL.getRouteKey())//到期后转发的路由键
.build();
}
/**
* 将订单队列绑定到交换机
*/
@Bean
Binding orderBinding(DirectExchange orderDirect,Queue orderQueue){
return BindingBuilder
.bind(orderQueue)
.to(orderDirect)
.with(QueueEnum.QUEUE_ORDER_CANCEL.getRouteKey());
}
/**
* 将订单延迟队列绑定到交换机
*/
@Bean
Binding orderTtlBinding(DirectExchange orderTtlDirect,Queue orderTtlQueue){
return BindingBuilder
.bind(orderTtlQueue)
.to(orderTtlDirect)
.with(QueueEnum.QUEUE_TTL_ORDER_CANCEL.getRouteKey());
}
}
- 此时在RabbitMQ管理页面可以看到以下交换机和队列;
- 交换机及队列说明如下:
-
- mall.order.direct(取消订单消息队列所绑定的交换机):绑定的队列为
mall.order.cancel
,一旦有消息以mall.order.cancel
为路由键发过来,会发送到此队列。 - mall.order.direct.ttl(订单延迟消息队列所绑定的交换机):绑定的队列为
mall.order.cancel.ttl
,一旦有消息以mall.order.cancel.ttl
为路由键发送过来,会转发到此队列,并在此队列保存一定时间,等到超时后会自动将消息发送到mall.order.cancel
(取消订单消息消费队列)。
- mall.order.direct(取消订单消息队列所绑定的交换机):绑定的队列为
- 添加延迟消息的发送者CancelOrderSender,用于向订单延迟消息队列(mall.order.cancel.ttl)里发送消息;
/**
* @auther macrozheng
* @description 取消订单消息的发出者
* @date 2018/9/14
* @github https://github.com/macrozheng
*/
@Component
public class CancelOrderSender {
private static Logger LOGGER =LoggerFactory.getLogger(CancelOrderSender.class);
@Autowired
private AmqpTemplate amqpTemplate;
public void sendMessage(Long orderId,final long delayTimes){
//给延迟队列发送消息
amqpTemplate.convertAndSend(QueueEnum.QUEUE_TTL_ORDER_CANCEL.getExchange(), QueueEnum.QUEUE_TTL_ORDER_CANCEL.getRouteKey(), orderId, new MessagePostProcessor() {
@Override
public Message postProcessMessage(Message message) throws AmqpException {
//给消息设置延迟毫秒值
message.getMessageProperties().setExpiration(String.valueOf(delayTimes));
return message;
}
});
LOGGER.info("send delay message orderId:{}",orderId);
}
}
- 添加取消订单消息的接收者CancelOrderReceiver,用于从取消订单的消息队列(mall.order.cancel)里接收消息;
/**
* @auther macrozheng
* @description 取消订单消息的处理者
* @date 2018/9/14
* @github https://github.com/macrozheng
*/
@Component
@RabbitListener(queues = "mall.order.cancel")
public class CancelOrderReceiver {
private static Logger LOGGER =LoggerFactory.getLogger(CancelOrderReceiver.class);
@Autowired
private OmsPortalOrderService portalOrderService;
@RabbitHandler
public void handle(Long orderId){
LOGGER.info("receive delay message orderId:{}",orderId);
portalOrderService.cancelOrder(orderId);
}
}
- 添加OmsPortalOrderService接口;
/**
* @auther macrozheng
* @description 前台订单管理Service
* @date 2018/8/30
* @github https://github.com/macrozheng
*/
public interface OmsPortalOrderService {
/**
* 根据提交信息生成订单
*/
@Transactional
CommonResult generateOrder(OrderParam orderParam);
/**
* 取消单个超时订单
*/
@Transactional
void cancelOrder(Long orderId);
}
- 添加OmsPortalOrderService的实现类OmsPortalOrderServiceImpl;
/**
* @auther macrozheng
* @description 前台订单管理Service
* @date 2018/8/30
* @github https://github.com/macrozheng
*/
@Service
public class OmsPortalOrderServiceImpl implements OmsPortalOrderService {
private static Logger LOGGER = LoggerFactory.getLogger(OmsPortalOrderServiceImpl.class);
@Autowired
private CancelOrderSender cancelOrderSender;
@Override
public CommonResult generateOrder(OrderParam orderParam) {
//todo 执行一系类下单操作,具体参考mall项目
LOGGER.info("process generateOrder");
//下单完成后开启一个延迟消息,用于当用户没有付款时取消订单(orderId应该在下单后生成)
sendDelayMessageCancelOrder(11L);
return CommonResult.success(null, "下单成功");
}
@Override
public void cancelOrder(Long orderId) {
//todo 执行一系类取消订单操作,具体参考mall项目
LOGGER.info("process cancelOrder orderId:{}",orderId);
}
private void sendDelayMessageCancelOrder(Long orderId) {
//获取订单超时时间,假设为60分钟
long delayTimes = 30 * 1000;
//发送延迟消息
cancelOrderSender.sendMessage(orderId, delayTimes);
}
}
- 添加OmsPortalOrderController定义接口;
/**
* @auther macrozheng
* @description 订单管理Controller
* @date 2018/8/30
* @github https://github.com/macrozheng
*/
@Controller
@Api(tags = "OmsPortalOrderController")
@Tag(name = "OmsPortalOrderController", description = "订单管理")
@RequestMapping("/order")
public class OmsPortalOrderController {
@Autowired
private OmsPortalOrderService portalOrderService;
@ApiOperation("根据购物车信息生成订单")
@RequestMapping(value = "/generateOrder", method = RequestMethod.POST)
@ResponseBody
public Object generateOrder(@RequestBody OrderParam orderParam) {
return portalOrderService.generateOrder(orderParam);
}
}
上面的代码核心展示了使用在处理订单逻辑中,向指定队列发送消息的过程,配置了该消息队列监听事件的处理方式。
但针对这里的业务场景,实际上是还需要配置一个定时任务,用来不断监听查看订单的支付状态,如果是已经支付则需要将延迟队列中的消息抛弃掉。
延迟消息功能演示
- 通过
/order/generateOrder
接口进行下单操作,注意这里已经将延迟消息时间设置为30秒;
- 经过30秒后,消息接收者会收到信息并进行处理。
项目源码地址
https://github.com/macrozheng/mall-learning/tree/teach/mall-tiny-07