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");
}
}
- 测试
@Test
void contextLoads3() {
orderService.makeOrderTTL("1","1",12);
}
- 打开rabbitmq服务,队列中的消息5s后自动加入死信queue中,5s后死信队列多了一条
设置最大长度
- 当队列中消息达到5条之后的都放在了死信队列中
//声明队列 给队列设置过期时间
@Bean
public Queue directTTLQueue(){
Map<String,Object> map = new HashMap<>();
//map.put("x-message-ttl",5000);//这里一定是int
map.put("x-max-length",5);
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);
}
- 测试运行(发送11条)
@Test
void contextLoads3() {
for (int i = 0; i < 11; i++) {
orderService.makeOrderTTL("1","1",12);
}
}
- 打开rabbitmq服务(正常队列只有5条,其余的都在死信队列中)
既设置过期时间又设置最大长度
@Bean
public Queue directTTLQueue(){
Map<String,Object> map = new HashMap<>();
map.put("x-message-ttl",5000);//这里一定是int
map.put("x-max-length",5);
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);
}
刚开始正常队列有5条,5秒后,这5条也到了死信队列中