springboot整合rabbitmq消息队列之TTL

一:队列统一过期

1.ttl在生产端编码

//队列名称
    public static final String TTL_QUEUE = "delay_queue";

    public static final String TTL_NAME = "delay_exchange";

    //ttl时间(毫秒)
    private static final int TTL_EXPIRATION = 10000;


    /*
    * 创建延迟队列
    */
    @Bean
    public Queue TTlQueue(){
        return QueueBuilder.durable(TTL_QUEUE).withArgument("x-message-ttl", TTL_EXPIRATION).build();
    }

    @Bean
    public TopicExchange TTlExchange(){
        return new TopicExchange(TTL_NAME);
    }

    //绑定
    @Bean
    public Binding TTlBinding(){
        return BindingBuilder.bind(TTlQueue()).to(TTlExchange()).with("*.ttt");
    }

2.测试

/*
        测试TTL
     */

    @Test
    void TTL() {

        rabbitTemplate.convertAndSend(RabbitMQConfig.TTL_NAME,"xiaomi.ttt","hello jsp!");
    }

二:消息单独过期

@Test
    void TTL() {


        //消息处理对象,设置一些消息的参数信息
        MessagePostProcessor messagePostProcessor= new MessagePostProcessor(){

            @Override
            public Message postProcessMessage(Message message) throws AmqpException {
                //设置message的信息
                message.getMessageProperties().setExpiration("5000");//消息的过期时间

                return message;
            }
        };

        rabbitTemplate.convertAndSend(RabbitMQConfig.TTL_NAME,"xiaomi.ttt","hello jsp!",messagePostProcessor);
    }

:如果想改时间就把原先的队列的删除,再运行!!!

你可能感兴趣的:(springboot,rabbitmq)