import com.rabbitmq.client.Channel; import org.springframework.amqp.core.Binding; import org.springframework.amqp.core.Exchange; import org.springframework.amqp.core.Message; import org.springframework.amqp.core.Queue; import org.springframework.amqp.core.TopicExchange; import org.springframework.amqp.rabbit.annotation.RabbitListener; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.io.IOException; import java.util.HashMap; import java.util.Map; @Configuration public class DemoMqConfig { // 监听队列消息 @RabbitListener(queues = "order.release.order.queue") public void listener(OrderEntity entity, Channel channel, Message message) throws IOException { System.out.println("收到过期的订单信息:准备关闭订单" + entity.getOrderSn()); // 可以通过 Message.getBody() 获取消息 System.out.println("收到过期的订单信息:准备关闭订单:" + message.getBody()); channel.basicAck(message.getMessageProperties().getDeliveryTag(), false); } @Bean public Queue orderDelayQueue() { Maparguments = 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); Queue queue = new Queue("order.delay.queue", true, false, false, arguments); return queue; } @Bean public Queue orderReleaseOrderQueue() { Queue queue = new Queue("order.release.order.queue", true, false, false); return queue; } @Bean public Exchange orderEventExchange() { TopicExchange exchange = new TopicExchange("order-event-exchange", true, false); return exchange; } @Bean public Binding orderCreateOrder() { Binding binding = new Binding("order.delay.queue", Binding.DestinationType.QUEUE, "order-event-exchange", "order.create.order", null); return binding; } @Bean public Binding orderReleaseOrder() { Binding binding = new Binding("order.release.order.queue", Binding.DestinationType.QUEUE, "order-event-exchange", "order.release.order", null); return binding; } }
创建订单,发送消息:
@Autowired RabbitTemplate rabbitTemplate; @ResponseBody @GetMapping("test/createOrder") public String createOrderTest() { // 订单下单成功 OrderEntity orderEntity = new OrderEntity(); orderEntity.setOrderSn(UUID.randomUUID().toString()); // 给MQ发送消息 rabbitTemplate.convertAndSend("order-event-exchange", "order.create.order", orderEntity); return "ok"; }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)