RabbitMQ延迟机制

五、延迟机制

5.1 延迟队列

  • 延迟队列——消息进入到队列之后,延迟指定的时间才能被消费者消费

  • AMQP协议和RabbitMQ队列本身是不支持延迟队列功能的,但是可以通过TTL(Time To Live)特性模拟延迟队列的功能

  • TTL就是消息的存活时间。RabbitMQ可以分别对队列和消息设置存活时间

    image-20200526162923111
    • 在创建队列的时候可以设置队列的存活时间,当消息进入到队列并且在存活时间内没有消费者消费,则此消息就会从当前队列被移除;
    • 创建消息队列没有设置TTL,但是消息设置了TTL,那么当消息的存活时间结束,也会被移除;
    • 当TTL结束之后,我们可以指定将当前队列的消息转存到其他指定的队列

5.2 使用延迟队列实现订单支付监控

5.2.1 实现流程图
image-20200526164139017
5.2.2 创建交换机和队列
1.创建路由交换机
image-20200526164349455
2.创建消息队列
image-20200526164546698
3.创建死信队列
image-20200526164941362
4.队列绑定
image-20200526165116155
/**
* 	发送消息
*/
public class SedMsg {
    public static void main(String[] args) throws Exception{
        String msg = "hello consumer";
        Connection connection = ConnectionUtils.getConnection();
        Channel channel1 = connection.createChannel();
        channel1.basicPublish("delay_exchange","k1",null,msg.getBytes());
        System.out.println("发送:"+msg);

    }
}

/**
* 接收消息
*/
public class SaveMsg {
    public static void main(String[] args) throws Exception {
        Connection connection = ConnectionUtils.getConnection();
        Channel channel = connection.createChannel();

        Consumer consumer = new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String msg = new String(body);
                System.out.println("接收:"+msg);
            }
        };

        channel.basicConsume("delay_queue2",true,consumer);
    }
}

posted @ 2021-01-12 12:05  codeFiler  阅读(394)  评论(0编辑  收藏  举报