监听队列 监听过期订单队列
package com.example.myorder.consumer; import org.springframework.amqp.rabbit.annotation.RabbitListener; import org.springframework.stereotype.Component; @Component public class ExpireConsumer { //监听过期订单队列 @RabbitListener(queues = "expire_queue") public void listenMessage(String orderId){ System.out.println("查询 orderId: "+orderId+"号订单状态,如果以支付无需处理,如果以支付则退回库存"); } //监听过期订单队列 @RabbitListener(queues = "delayed_queue") public void listenMessage2(String orderId){ System.out.println("查询 orderId: "+orderId+"号订单状态,如果以支付无需处理,如果以支付则退回库存"); } }
利用插件的延迟队列 创建延迟交换机的方式不一样
package com.example.myorder; import org.springframework.amqp.core.*; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.util.HashMap; import java.util.Map; @Configuration public class RabbitConfig2 { private final String DELAYED_EXCHANGE = "delayed_exchange"; private final String DELAYED_QUEUE = "delayed_queue"; //延迟交换机 @Bean(DELAYED_EXCHANGE) public Exchange delayedExchange(){ //创建自定义交换机 Map args=new HashMap(); args.put("x-delayed-type","topic"); //交换机名 类型 是否持久化 是否自动删除 return new CustomExchange( DELAYED_EXCHANGE, "x-delayed-message", true, false, args); } //延迟队列 @Bean(DELAYED_QUEUE) public Queue delayedQueue() { return QueueBuilder .durable(DELAYED_QUEUE) .build(); } //绑定 @Bean public Binding bindingDelayedQueue(@Qualifier(DELAYED_EXCHANGE) Exchange exchange, @Qualifier (DELAYED_QUEUE) Queue queue){ return BindingBuilder .bind(queue) .to(exchange) .with("order_routing") .noargs(); } } 控制类 package com.example.myorder.controller; import org.springframework.amqp.AmqpException; import org.springframework.amqp.core.Message; import org.springframework.amqp.core.MessagePostProcessor; import org.springframework.amqp.core.MessageProperties; import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; @RestController public class OrderController {} @Autowired private RabbitTemplate rabbitTemplate;
//下单 @GetMapping("/place2/{orderId}") public String placeOrder2(@PathVariable String orderId) { System.out.println("处理订单数据"); //设置消息的延迟时间为10s MessagePostProcessor messagePostProcessor = new MessagePostProcessor() { @Override public Message postProcessMessage(Message message) throws AmqpException { message.getMessageProperties().setDelay(10000); return message; } }; //将订单Id发送到订单队列 rabbitTemplate.convertAndSend( "delayed_exchange", "order_routing", orderId, messagePostProcessor); return "下单成功,修改库存"; }
}