RabbitMQ的延迟队列实现[死信队列](笔记二)

上一篇已经讲述了实现死信队列的rabbitMQ服务配置,可以点击: RabbitMQ的延迟队列实现(笔记一)

目录

搭建一个新的springboot项目

1.相关核心依赖如下

xml 复制代码
		<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!--mq依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-amqp</artifactId>
        </dependency>

        <!-- lombok 依赖 -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

2.配置文件如下

yml 复制代码
server:
  port: 8080

spring:
  #MQ配置
  rabbitmq:
    host: ip
    port: 5673
    username: root
    password: root+12345678

3.目录结构

模仿订单延迟支付过期操作

1.创建OrderMqConstant.java,设定常量,代码如下

java 复制代码
package com.example.aboutrabbit.constant;
/**
 * @description 订单队列常量
 * @author lxh
 * @time 2024/2/7 17:05
 */
public interface OrderMqConstant {
    /**
     *交换机
     */
    String exchange = "order-event-exchange";
    /**
     * 队列
     */
    String orderQueue = "order.delay.queue";
    /**
     * 路由
     */
    String orderDelayRouting = "order.delay.routing";
}

2.创建OrderDelayConfig.java,配置绑定

java 复制代码
package com.example.aboutrabbit.config;

import com.example.aboutrabbit.constant.OrderMqConstant;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.CustomExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * @author lxh
 * @description 配置绑定
 * @time 2024/2/7 17:15
 **/
@Configuration
public class OrderDelayConfig {
    /**
     * 延时队列交换机
     * 注意这里的交换机类型:CustomExchange
     */
    @Bean
    public CustomExchange maliceDelayExchange() {
        Map<String, Object> args = new HashMap<>();
        args.put("x-delayed-type", "direct");
        // 属性参数 交换机名称 交换机类型 是否持久化 是否自动删除 配置参数
        return new CustomExchange(OrderMqConstant.exchange, "x-delayed-message", true, false, args);
    }

    /**
     * 延时队列
     */
    @Bean
    public Queue maliceDelayQueue() {
        // 属性参数 队列名称 是否持久化
        return new Queue(OrderMqConstant.orderQueue, true);
    }

    /**
     * 给延时队列绑定交换机
     */
    @Bean
    public Binding maliceDelayBinding() {
        return BindingBuilder.bind(maliceDelayQueue()).to(maliceDelayExchange()).with(OrderMqConstant.orderDelayRouting).noargs();
    }
}

3、创建 OrderMQReceiver.java监听过期的消息

java 复制代码
package com.example.aboutrabbit.config;

import com.example.aboutrabbit.constant.OrderMqConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author lxh
 * @description 接收过期订单
 * @time 2024/2/7 17:21
 **/
@Component
@Slf4j
public class OrderMQReceiver {
    @RabbitListener(queues = OrderMqConstant.orderQueue)
    public void onDeadMessage(String infoId) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        log.info("收到头框过期时间:{},消息是:{}", sdf.format(new Date()), infoId);
    }
}

4.分别创建MQService.java和MQServiceImpl.java,处理消息发送

java 复制代码
package com.example.aboutrabbit.service;
/**
 * @description MQ发消息服务
 * @author lxh
 * @time 2024/2/7 17:26
 */
public interface MQService {
    /**
     * 发送或加队列
     * @param orderId 订单主键
     * @param time 毫秒
     */
    void sendOrderAddInfo(Long orderId, Integer time);
}
java 复制代码
package com.example.aboutrabbit.service.impl;

import com.example.aboutrabbit.constant.OrderMqConstant;
import com.example.aboutrabbit.service.MQService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author lxh
 * @description MQ发消息服务实现
 * @time 2024/2/7 17:26
 **/
@Slf4j
@Service
public class MQServiceImpl implements MQService {
    @Autowired
    private RabbitTemplate rabbitTemplate;
    /**
     * 发送或加队列
     * @param orderId 订单主键
     * @param time 毫秒
     */
    @Override
    public void sendOrderAddInfo(Long orderId, Integer time) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        log.info("过期队列添加|添加时间:{},内容是:{},过期毫秒数:{}",sdf.format(new Date()),orderId, time);
        rabbitTemplate.convertAndSend(OrderMqConstant.exchange, OrderMqConstant.orderDelayRouting,
                orderId,
                message -> {
                    message.getMessageProperties().setDelay(time);
                    return message;
                }
        );
    }
}

5.创建控制层进行测试TestController.java

java 复制代码
package com.example.aboutrabbit.controller;

import com.example.aboutrabbit.service.MQService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;


/**
 * @author lxh
 * @description 测试
 * @time 2024/2/7 17:36
 **/
@RestController
@RequestMapping("/test")
public class TestController {
    @Autowired
    private MQService mqService;
    @GetMapping("/send")
    public String list(@RequestParam Long orderId,@RequestParam Integer fenTime) {
        //默认
        Integer time = fenTime * 60 * 1000;
        mqService.sendOrderAddInfo(orderId, time);
        return "success";
    }
}

6.全部结构展示

启动项目进行测试

1.示例:localhost:8080/test/send?orderId=1&fenTime=1

订单id为1的延迟一分钟过期,如下

2.查看日志

相关推荐
麦兜*19 分钟前
MongoDB Atlas 云数据库实战:从零搭建全球多节点集群
java·数据库·spring boot·mongodb·spring·spring cloud
麦兜*24 分钟前
MongoDB 在物联网(IoT)中的应用:海量时序数据处理方案
java·数据库·spring boot·物联网·mongodb·spring
汤姆yu26 分钟前
基于springboot的毕业旅游一站式定制系统
spring boot·后端·旅游
计算机毕业设计木哥1 小时前
计算机毕设选题推荐:基于Java+SpringBoot物品租赁管理系统【源码+文档+调试】
java·vue.js·spring boot·mysql·spark·毕业设计·课程设计
hdsoft_huge11 小时前
Java & Spring Boot常见异常全解析:原因、危害、处理与防范
java·开发语言·spring boot
AD钙奶-lalala14 小时前
SpringBoot实现WebSocket服务端
spring boot·后端·websocket
毕设源码-朱学姐14 小时前
【开题答辩全过程】以 4S店汽车维修保养管理系统为例,包含答辩的问题和答案
java·spring boot·汽车
BXCQ_xuan15 小时前
软件工程实践二:Spring Boot 知识回顾
java·spring boot·后端
wuxuanok16 小时前
SpringBoot -原理篇
java·spring boot·spring
云动雨颤16 小时前
Spring Boot配置优化:Tomcat+数据库+缓存+日志,全场景教程
数据库·spring boot·tomcat