RabbitMQ 之延时队列关闭订单

RabbitMQ 之延时队列关闭订单,第1张

RabbitMQ 之延时队列关闭订单

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() {
        Map 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);
        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";
    }

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5481546.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-12
下一篇 2022-12-12

发表评论

登录后才能评论

评论列表(0条)

保存