1. 简介
DLX: Dead-Letter-Exchange 死信交换器,死信邮箱
2.代码示例
java
@Configuration
public class RabbitConfig {
final static String exchangeNormalName = "exchange.dlx.normal";
final static String queueNormalName = "queue.dlx.normal";
final static String exchangeDeadName = "exchange.dlx.dead";
final static String queueDeadName = "queue.dlx.dead";
//正常交换机
@Bean
public DirectExchange normalExchange(){
return ExchangeBuilder.directExchange(exchangeNormalName).build();
}
//正常队列
@Bean
public Queue normalQueue(){
Map<String, Object> map = new HashMap<>();
map.put("x-message-ttl", 20000);//设置20s的过期时间
map.put("x-dead-letter-exchange", exchangeDeadName);//设置死信交换机名字
map.put("x-dead-letter-routing-key", "error");//设置死信交换机路由k
return QueueBuilder.durable(queueNormalName)
.withArguments(map)
.build();
}
@Bean
public Binding normalBinding(DirectExchange normalExchange, Queue normalQueue){
return BindingBuilder.bind(normalQueue).to(normalExchange).with("order");
}
//死信交换机
@Bean
public DirectExchange dlxExchange(){
return ExchangeBuilder.directExchange(exchangeDeadName).build();
}
//死信队列
@Bean
public Queue dlxQueue(){
return QueueBuilder.durable(queueDeadName).build();
}
@Bean
public Binding dlxBinding(DirectExchange dlxExchange, Queue dlxQueue){
return BindingBuilder.bind(dlxQueue).to(dlxExchange).with("error");
}
}
如上,设置普通交换机把过期内容放置到死信交换机中去。最重要的几行代码
java
map.put("x-message-ttl", 20000);//设置20s的过期时间
map.put("x-dead-letter-exchange", exchangeDeadName);//设置死信交换机名字
map.put("x-dead-letter-routing-key", "error");//设置死信交换机路由k
3.测试结果
经过20s之后,如下,将普通队列的信息放入死信队列中
其中TTL代表x-message-ttl,DLX代表x-dead-letter-exchange,DLK代表x-dead-letter-routing-key
4.单条消息
上方是将整个队列设置过期时间,也可以将单条消息设置过期时间,即不给整个队列设置过期时间
java
//map.put("x-message-ttl", 20000);//设置20s的过期时间
map.put("x-dead-letter-exchange", exchangeDeadName);//设置死信交换机名字
map.put("x-dead-letter-routing-key", "error");//设置死信交换机路由k
而是在消息体中设置过期时间
java
@Component
@Slf4j
public class MessageService {
@Autowired
private RabbitTemplate rabbitTemplate;
public void senMsg() throws InterruptedException {
//定义消息
String msg="单条消息过期时间test";
MessageProperties messageProperties = new MessageProperties();
messageProperties.setExpiration("10000"); //10s
Message message= MessageBuilder.withBody(msg.getBytes()).andProperties(messageProperties).build();
//发消息
rabbitTemplate.convertAndSend("exchange.dlx.normal","order",message);
log.info("消息发送完毕,发送时间为:{}", new Date());
}
}