死信队列
消息成为死信的三种情况:
-
队列消息长度到达限制;
-
消费者拒接消费消息,basicNack/basicReject,并且不把消息重新放入原目标队列,requeue=false;
-
原队列存在消息过期设置,消息到达超时时间未被消费;
队列绑定死信交换机:
给队列设置参数: x-dead-letter-exchange 和 x-dead-letter-routing-key
package com.ykq.config;
import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class RabbitConfig {
private final String EXCHANGE="exchange";
private final String DEAD_EXCHANGE="dead_exchange";
private final String QUEUE="queue";
private final String DEAD_QUEUE="dead_queue";
@Bean
public Queue queue(){
return QueueBuilder
.durable(QUEUE)
.withArgument("x-message-ttl",20000)
.withArgument("x-max-length",10)
.withArgument("x-dead-letter-exchange",DEAD_EXCHANGE)
.withArgument("x-dead-letter-routing-key","error")
.build()
;
}
@Bean
public Queue dead_queue() {
return QueueBuilder.durable(DEAD_QUEUE).build();
}
@Bean
public Exchange exchange(){
return ExchangeBuilder.directExchange(EXCHANGE).build();
}
@Bean
public Exchange dead_exchange(){
return ExchangeBuilder.directExchange(DEAD_EXCHANGE).build();
}
@Bean
public Binding binding(){
return BindingBuilder.bind(queue()).to(exchange()).with("error").noargs();
}
@Bean
public Binding dead_binding(){
return BindingBuilder.bind(dead_queue()).to(dead_exchange()).with("error").noargs();
}
}
延迟队列
RabbitMQ----延迟队列
1.为什么需要使用延迟队列?适用于什么场景?
订单下单之后30分钟后,如果用户没有付钱,则系统自动取消订单。
这样类似的需求是我们经常会遇见的问题。最常用的方法是定期轮训数据库,设置状态。在数据量小的时候并没有什么大的问题,但是数据量一大轮训数据库的方式就会变得特别耗资源。当面对千万级、上亿级数据量时,本身写入的IO就比较高,导致长时间查询或者根本就查不出来。通过使用延迟队列来解决这种问题。
延迟队列就是给队列设置了一个过期时间,延迟队列一般都是配合TTL和死信队列来实现的。
上代码实现:
在原有项目上创建消费者子项目
创建消费者:
@Component
public class MyListener {
@RabbitListener(queues = "dead_queue")
public void listener(Message message, Channel channel){
System.out.println("三十分钟没有处理订单,取消订单");
try {
channel.basicAck(message.getMessageProperties().getDeliveryTag(),true);
} catch (IOException e) {
try {
channel.basicNack(message.getMessageProperties().getDeliveryTag(),true,true);
} catch (IOException ioException) {
}
}
}
}
主启动类:
@SpringBootApplication
public class ConsumerApp {
public static void main(String[] args) {
SpringApplication.run(com.ConsumerApp.class,args);
}
}
发送信息到交换机,创建交换机在上面,点这里跳转
@Test
public void testDeadQueue() {
rabbitTemplate.convertAndSend("exchange", "info", "下单成功。");
}
先开启消费者,启动消费者主启动类,在启动测试单元。
此时死信队列中是没有信息的。
假设等待5秒钟,看看信息是否被消费者消费掉了。
得到结果,信息被消费者得到了。