Springboot 集成Rabbitmq之延时队列

1.首先确保已经引入了Spring AMQP和RabbitMQ的相关依赖:

复制代码
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
  1. 创建一个普通队列并设置TTL(消息过期时间),同时声明一个死信交换机和死信队列,当普通队列中的消息过期后会自动转发到死信队列:

    @Bean
    Queue normalQueue() {
    Map<String, Object> args = new HashMap<>();
    args.put("x-message-ttl", 60000); // 消息有效期为60秒
    args.put("x-dead-letter-exchange", "delayExchange"); // 设置死信交换机
    args.put("x-dead-letter-routing-key", "delayQueue"); // 设置死信路由键
    return new Queue("normalQueue", true, false, false, args);
    }

    @Bean
    Queue delayQueue() {
    return new Queue("delayQueue", true, false, false);
    }

    @Bean
    DirectExchange delayExchange() {
    return new DirectExchange("delayExchange");
    }

    @Bean
    Binding delayBinding(DirectExchange delayExchange, Queue delayQueue) {
    return BindingBuilder.bind(delayQueue).to(delayExchange).with("delayQueue");
    }

3.在delayQueue上监听消息,这样当消息从normalQueue过期转移到delayQueue后,消费者就会接收到这条消息:

复制代码
@RabbitListener(queues = "delayQueue")
public void processDelayMessage(String message) {
    System.out.println("Processing delayed message: " + message);
    // 在这里处理延时后的消息
}

4.发送消息到normalQueue:

复制代码
@Autowired
private RabbitTemplate rabbitTemplate;

public void sendMessage(String message) {
    rabbitTemplate.convertAndSend("normalQueue", message);
}

以上代码示例中,正常的消息会被发送到normalQueue,如果在指定的TTL时间内未被消费,则该消息会作为死信转发到delayExchange,然后根据路由键路由到delayQueue,最终由监听delayQueue的消费者进行处理,从而实现了消息的延时处理。

相关推荐
万亿少女的梦1681 分钟前
基于Spring Boot与Vue的繁星技术论坛系统设计与实现
java·spring boot·mysql·vue·系统设计
万亿少女的梦16818 小时前
基于SpringBoot的考研学习交流系统设计与开发
spring boot·mysql·vue·系统设计·论坛系统
二宝哥21 小时前
创建Gradle多模块SpringBoot项目
java·spring boot·后端
杨运交1 天前
[044][Web模块]基于 Google Authenticator 的 TOTP 双因素认证框架设计与实现
spring boot
二宝哥1 天前
springboot项目使用Gradle工具实现依赖版本控制
java·spring boot·后端·gradle·版本
卓怡学长1 天前
w273基于springboot的智能笔记的开发与应用
java·spring boot·spring·intellij-idea
Kyrie_Li1 天前
Spring Boot Kafka 生产级配置全解析:从入门到精通
spring boot·后端·kafka
小强库计算机毕业设计2 天前
源码分享Spring Boot + Vue3 的校园社团管理系统
java·spring boot·后端·计算机毕业设计
格子软件2 天前
2026年分布式GEO代理流量调度:源码级状态机防重挂实战
java·vue.js·人工智能·spring boot·分布式·vue