1. 程式人生 > 其它 >rabbitmq-高階(死信佇列)

rabbitmq-高階(死信佇列)

  • 宣告一個DeadQueue
@Configuration
public class DeadRabbitmqConfiguration {
    //宣告交換機
    @Bean
    public DirectExchange deadDirect(){
        return new DirectExchange("dead_direct_exchange",true,false);
    }

    //宣告佇列 給佇列設定過期時間
    @Bean
    public Queue deadQueue(){
        return new Queue("dead.direct.queue",true);
    }

    @Bean
    public Binding deadBinding(){
        return BindingBuilder.bind(deadQueue()).to(deadDirect()).with("dead");
    }
}
  • 設定死信交換機引數和死信key引數,主要看directTTLQueue()方法
@Configuration
public class TTLRabbitmqConfiguration {
    //宣告交換機
    @Bean
    public DirectExchange ttlDirectExchange(){

        return new DirectExchange("ttl_order_exchange",true,false);
    }

    //宣告佇列 給佇列設定過期時間
    @Bean
    public Queue directTTLQueue(){
        Map<String,Object> map = new HashMap<>();
        map.put("x-message-ttl",5000);//這裡一定是int
        map.put("x-dead-letter-exchange","dead_direct_exchange");
        //因為是direct模式,所以需要設定一個key,fanout模式不需要配置
        map.put("x-dead-letter-routing-key","dead");
        return new Queue("ttl.direct.queue",true,false,false,map);
    }

    //具體訊息
    @Bean
    public Queue directTTLMessageQueue(){
        return new Queue("ttl.message.direct.queue",true);
    }

    //完成交換機和佇列繫結
    @Bean
    public Binding directTTLBinding(){
        return BindingBuilder.bind(directTTLQueue()).to(ttlDirectExchange()).with("ttl");
    }

    @Bean
    public Binding directMsgBinding(){
        return BindingBuilder.bind(directTTLMessageQueue()).to(ttlDirectExchange()).with("ttlmessage");
    }
}
  • 佇列中的訊息5s後自動加入死信queue中,5s後死信佇列多了一條