RabbitMQ实现延迟队列一:在队列上设置TTL
Publish --> delaysync.exchange --> delay.5m.queue(延迟队列) --> delay.exchange --> test.queue(正常队列) --> Consumer
//延迟队列start
Map<String,Object> map = new HashMap<String,Object>();
map.put("x-message-ttl", 10000);//消息过期时间
map.put("x-max-length", 500000);//最大积压的消息个数
map.put("x-dead-letter-exchange", "delay.exchange");//消息过期后会投递到delay.exchange
channel.queueDeclare("delay.5m.queue", true, false, false, map);
RabbitMQ实现延迟队列二:在消息上设置TTL
Publish --> default exchange --> delay_queue(延迟队列) --> amq.direct --> message_ttl_queue(正常队列) --> Consumer
队列:
//延迟队列
Map<String,Object> arguments = new HashMap<String,Object>();
arguments.put("x-dead-letter-exchange", "amq.direct");//消息过期后会投递到amq.direct
arguments.put("x-dead-letter-routing-key", "message_ttl_routingKey");//出现dead letter之后将重新按照指定的routing-key发送
channel.queueDeclare("delay_queue", true, false, false, arguments);
消息发送:
//设置延迟属性
AMQP.BasicProperties.Builder builder = new AMQP.BasicProperties.Builder();
//deliveryMode:将消息标记为持久(值为2)或瞬态(任何其他值)
AMQP.BasicProperties properties = builder.expiration("10000").deliveryMode(2).build();
channel.basicPublish("", "delay_queue", properties, msg.getBytes());