RabbitMQ队列延迟

RabbitMQ队列延迟

1. 场景:

“订单下单成功后,15分钟未支付自动取消”  
1.传统处理超时订单
     采取定时任务轮训数据库订单,并且批量处理。其弊端也是显而易见的;对服务器、数据库性会有很大的要求,
     并且当处理大量订单起来会很力不从心,而且实时性也不是特别好。当然传统的手法还可以再优化一下,
     即存入订单的时候就算出订单的过期时间插入数据库,设置定时任务查询数据库的时候就只需要查询过期了的订单,
     然后再做其他的业务操作
   2.rabbitMQ延时队列方案
     一台普通的rabbitmq服务器单队列容纳千万级别的消息还是没什么压力的,而且rabbitmq集群扩展支持的也是非常好的,
     并且队列中的消息是可以进行持久化,即使我们重启或者宕机也能保证数据不丢失

2. TTL和DLX

   rabbitMQ中是没有延时队列的,也没有属性可以设置,只能通过死信交换器(DLX)和设置过期时间(TTL)结合起来实现延迟队列
   1.TTL
     TTL是Time To Live的缩写, 也就是生存时间。
     RabbitMq支持对消息和队列设置TTL,对消息这设置是在发送的时候指定,对队列设置是从消息入队列开始计算, 只要超过了队列的超时时间配置, 那么消息会自动清除。
     如果两种方式一起使用消息对TTL和队列的TTL之间较小的为准,也就是消息5s过期,队列是10s,那么5s的生效。
     默认是没有过期时间的,表示消息没有过期时间;如果设置为0,表示消息在投递到消费者的时候直接被消费,否则丢弃。
     设置消息的过期时间用 x-message-ttl 参数实现,单位毫秒。
     设置队列的过期时间用 x-expires 参数,单位毫秒,注意,不能设置为0。
   2.DLX和死信队列
     DLX即Dead-Letter-Exchange(死信交换机),它其实就是一个正常的交换机,能够与任何队列绑定。
     死信队列是指队列(正常)上的消息(过期)变成死信后,能够后发送到另外一个交换机(DLX),然后被路由到一个队列上,
     这个队列,就是死信队列
     成为死信一般有以下几种情况:
     消息被拒绝(basic.reject or basic.nack)且带requeue=false参数
     消息的TTL-存活时间已经过期
     队列长度限制被超越(队列满)
    
     注1:如果队列上存在死信, RabbitMq会将死信消息投递到设置的DLX上去 ,
     注2:通过在队列里设置x-dead-letter-exchange参数来声明DLX,如果当前DLX是direct类型还要声明
          x-dead-letter-routing-key参数来指定路由键,如果没有指定,则使用原队列的路由键
   

3. 延迟队列

   通过DLX和TTL模拟出延迟队列的功能,即,消息发送以后,不让消费者拿到,而是等待过期时间,变成死信后,发送给死信交换机再路由到死信队列进行消费
  
   注1:延迟队列(即死信队列)产生流程见“images/01 死信队列产生流程.png”

4. 开发步骤

   1.生产者创建一个正常消息,并添加消息过期时间/死信交换机/死信路由键这3个参数
     关键代码1
     new Queue(name, durable, exclusive, autoDelete, arguments);
     new Queue(NORMAL_QUEUE, true, false, false, map)
     参数说明:
     name:队列名字
     durable:true则持久队列
     exclusive:如果我们声明一个排他队列(该队列将仅由声明者的连接使用),则为true
     autoDelete:服务器不再使用时应删除队列,则为true
     arguments:用于声明队列的参数
       map.put("x-message-ttl", 10000);//message在该队列queue的存活时间最大为10秒
       map.put("x-dead-letter-exchange", DELAY_EXCHANGE); //x-dead-letter-exchange参数是设置该队列的死信交换器(DLX)
       map.put("x-dead-letter-routing-key", DELAY_ROUTING_KEY);//x-dead-letter-routing-key参数是给这个DLX指定路由键
     关键代码2
     new DirectExchange(NORMAL_EXCHANGE, true, false);
   2.消费者A
     正常情况下,由消费者A去消费队列“normal-queue”中的消息,但实际上没有,而是等消息过期
   3.消费者B
     消息过期后,变成死信,根据配置会被投递到DLX,然后根据死信路由键投到死信队列(即延时队列)中
 

5. 子模块间共享Model

   1.创建公共子模块common
     添加公共的JavaBean对象,并使用lombok简化代码
     @Data:会为类的所有属性自动生成setter/getter、equals、canEqual、hashCode、toString方法
     @NoArgsConstructor:无参构造器
     @AllArgsConstructor:全参构造器
    
   2.主模块
     <!-- 1.packaging模式改为pom -->
     <packaging>pom</packaging>
     <!-- 2.添加子模块 -->
     <modules>
        <module>rabbitmq-provider</module>
        <module>rabbitmq-consumer</module>
        <module>common</module>
     </modules>
    
   3.各子模块
     <!-- 1.packaging模式改为jar -->
     <packaging>jar</packaging>
   4.配置公共common模块
  
   在主模块的POM的<dependencies>中添加公共子模块common
   <dependencies>
     <!--添加子模块common-->
     <dependency>
       <groupId>com.zking</groupId>
       <artifactId>common</artifactId>
       <version>0.0.1-SNAPSHOT</version>
     </dependency>
     ...
   </dependencies>
 

看代码

创建一个工程rabbitmq03  ,普通maven项目
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.2.2.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
  </parent>
  <groupId>com.yuan</groupId>
  <artifactId>rabbitmq03</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <name>rabbitmq03</name>
  <packaging>pom</packaging>
  <description>Demo project for Spring Boot</description>

  <properties>
    <java.version>1.8</java.version>
  </properties>

  <modules>
    <module>rabbitmq-provider</module>
    <module>rabbitmq-consumer</module>
  </modules>

  <dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-amqp</artifactId>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
      <version>1.18.10</version>
      <scope>provided</scope>
    </dependency>

  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
      </plugin>
    </plugins>
  </build>

</project>
创建生产者模块rabbitmq-provider
RabbitMQ队列延迟
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>com.yuan</groupId>
        <artifactId>rabbitmq03</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>
    <artifactId>rabbitmq-provider</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>rabbitmq-provider</name>
    <description>子模块-生产者</description>
    <packaging>jar</packaging>
</project>
QueueDelayConfig


package com.yuan.rabbitmqprovider.rabbitmq;


import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.lang.model.element.NestingKind;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class QueueDelayConfig {

    /**
     * 定义正常的队列、交换机、路由键
     */
    public static final String NORMAL_QUEUE="normal-queue";
    public static final String NORMAL_EXCHANGE="normal-exchange";
    public static final String NORMAL_ROUTINGKEY="normal-routingkey";

    /**
     * 定义死信的队列、交换机、路由键
     */
    public static final String DELAY_QUEUE="delay-queue";
    public static final String DELAY_EXCHANGE="delay-exchange";
    public static final String DELAY_ROUTINGKEY="delay-routingkey";


    /**
     * 定义正常队列
     * @return
     */
    @Bean
    public Queue normalQueue(){
        //设定消息过期时间/死信交换机/死信路由键3个参数
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("x-message-ttl", 15000);//message在该队列queue的存活时间最大为15秒
        map.put("x-dead-letter-exchange", DELAY_EXCHANGE); //x-dead-letter-exchange参数是设置该队列的死信交换器(DLX)
        map.put("x-dead-letter-routing-key", DELAY_ROUTINGKEY);//x-dead-letter-routing-key参数是给这个DLX指定路由键

        return new Queue(NORMAL_QUEUE, true, false, false, map);
    }

    @Bean
    public DirectExchange normalExchange(){
        return new DirectExchange(NORMAL_EXCHANGE, true, false);
    }

    @Bean
    public Binding normalRoutingkey(){
        return BindingBuilder.bind(normalQueue())
                .to(normalExchange())
                .with(NORMAL_ROUTINGKEY);
    }


    /**
     * 定义死信队列
     */
    @Bean
    public Queue delayQueue(){
        return new Queue(DELAY_QUEUE, true);
    }

    @Bean
    public DirectExchange delayExchange(){
        return new DirectExchange(DELAY_EXCHANGE);
    }

    @Bean
    public Binding delayRoutingkey(){
        return BindingBuilder.bind(delayQueue())
                .to(delayExchange())
                .with(DELAY_ROUTINGKEY);
    }




}
SendController


package com.yuan.rabbitmqprovider.controller;


import com.yuan.rabbitmqprovider.rabbitmq.QueueDelayConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

@RestController
@Slf4j
public class SendController  {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @RequestMapping("/sender")
    public Map<String, Object> sender(){
        Map<String, Object> data = this.createData();

        rabbitTemplate.convertAndSend(QueueDelayConfig.NORMAL_EXCHANGE,
                QueueDelayConfig.NORMAL_ROUTINGKEY,data);
        Map<String, Object> result = new HashMap<String, Object>();
    result.put("msg","OK");
    result.put("code","1");
    return result;
    }



    private Map<String, Object> createData(){
        Map<String, Object> map = new HashMap<String, Object>();

        String date = LocalDateTime.now().format(DateTimeFormatter.BASIC_ISO_DATE.
                ofPattern("yyyy-MM-dd HH:mm:ss"));
        map.put("msg","hello rabbitmq!!");
        map.put("success",true);
        map.put("createdate", date);


        return map;
    }



}
最后配置一下yml文件
server:
  port: 8081
  servlet:
    context-path: /rabbitmq-provider
spring:
  rabbitmq:
    virtual-host: /
    username: guest
    password: guest
    host: 192.168.238.129
    port: 5672
创建消费者模块rabbitmq-consumer
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>com.yuan</groupId>
        <artifactId>rabbitmq03</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>
    <artifactId>rabbitmq-consumer</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>rabbitmq-consumer</name>
    <description>子模块-消费者</description>
    <packaging>jar</packaging>
</project>
QueueRecevier
package com.yuan.rabbitmqconsumer.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
@Slf4j
@RabbitListener(queues = {"delay-queue"})  //消费端监听队列,如果delay-queue死信队列中有消息过来就会被消费掉
public class QueueRecevier {

    @RabbitHandler
    public void handlerMessage(Map<String, Object> data){
        log.info("QueueRecevier.handlerMessage,data={}",data);
    }




}
标红处的log使用需要下载一个插件Lombok



直接右边install, 然后重启idea


yml文件配置

server:
  port: 8082
  servlet:
    context-path: /rabbitmq-consumer
spring:
  rabbitmq:
    virtual-host: /
    username: guest
    password: guest
    host: 192.168.238.129
    port: 5672
启动生产者,访问http://localhost:8081/rabbitmq-provider/sender  发送请求。
 
 
RabbitMQ队列延迟
 
生产端推送消息到正常队列等待被消费,我们设定的过期时间是15秒,,,
RabbitMQ队列延迟
RabbitMQ队列延迟

 启动消费端,消费端会根据我们设定的监听去监听队列中是否有消息有则会被消费掉。。

RabbitMQ队列延迟

6. json转换

   1.生产者
     @Bean
     public RabbitTemplate createRabbitTemplate(ConnectionFactory connectionFactory, Jackson2JsonMessageConverter jackson2JsonMessageConverter) {
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        rabbitTemplate.setMessageConverter(jackson2JsonMessageConverter);//指定json转换器
        return rabbitTemplate;
     }
   2.消费者
     @Bean
     public SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory(ConnectionFactory connectionFactory, Jackson2JsonMessageConverter jackson2JsonMessageConverter) {
        SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
        factory.setConnectionFactory(connectionFactory);
        factory.setMessageConverter(jackson2JsonMessageConverter);
        return factory;
    
}
 
创建公共子模块common-vo
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>com.yuan</groupId>
        <artifactId>rabbitmq03</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>
    <artifactId>common-vo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>common-vo</name>
    <packaging>jar</packaging>
    <description>公共子模块</description>



</project>

创建一个model的Package,创建一个Order
package com.yuan.commonvo.model;

import lombok.Data;

import java.lang.reflect.ParameterizedType;
import java.util.Date;


@Data
public class Order {

    private  long orderId;
    private  String orderNo;
    private Date createdate;


}

vo包下创建一个OrderVo

 
package com.yuan.commonvo.vo;

import com.yuan.commonvo.model.Order;


public class OrderVo extends Order {

}

完了之后在父模块中添加common-vo子模块的一个pom依赖
<modules>
    <module>rabbitmq-provider</module>
    <module>rabbitmq-consumer</module>
    <module>common-vo</module>
  </modules>
<dependency>  <groupId>com.yuan</groupId>  <artifactId>common-vo</artifactId>  <version>0.0.1-SNAPSHOT</version></dependency>

修改生产者SendController
 @RequestMapping("/sender")
    public Map<String, Object> sender(){
//        Map<String, Object> data = this.createData();

        OrderVo orderVo = new OrderVo();
        orderVo.setOrderId(1);
        orderVo.setOrderNo("P001");

        rabbitTemplate.convertAndSend(QueueDelayConfig.NORMAL_EXCHANGE,
                QueueDelayConfig.NORMAL_ROUTINGKEY,orderVo);
        Map<String, Object> result = new HashMap<String, Object>();
    result.put("msg","OK");
    result.put("code","1");
    return result;
    }

添加QueueProviderMessageConvert
package com.yuan.rabbitmqprovider.rabbitmq;import org.springframework.amqp.rabbit.connection.ConnectionFactory;import org.springframework.amqp.rabbit.core.RabbitTemplate;import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;@Configurationpublic class QueueProviderMessageConvert {    @Bean    public RabbitTemplate createRabbitTemplate(ConnectionFactory connectionFactory){        RabbitTemplate rabbitTemplate=new RabbitTemplate();        rabbitTemplate.setConnectionFactory(connectionFactory);        rabbitTemplate.setMessageConverter(jackson2JsonMessageConverter());        return  rabbitTemplate;    }    @Bean    public Jackson2JsonMessageConverter jackson2JsonMessageConverter(){        return new Jackson2JsonMessageConverter();    }}

 修改消费端QueueRecevier
package com.yuan.rabbitmqconsumer.controller;


import com.yuan.commonvo.vo.OrderVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

@Component
@Slf4j
@RabbitListener(queues = {"delay-queue"})  //消费端监听队列,如果delay-queue死信队列中有消息过来就会被消费掉
public class QueueRecevier {

    @RabbitHandler
    public void handlerMessage(OrderVo orderVo){
        log.info("QueueRecevier.handlerMessage,data={}",orderVo);
    }




}

添加消费端QueueRecevierMessageConvert


 
package com.yuan.rabbitmqconsumer.controller;import org.springframework.amqp.rabbit.connection.ConnectionFactory;import org.springframework.amqp.rabbit.core.RabbitTemplate;import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;@Configurationpublic class QueueRecevierMessageConvert {    @Bean    public RabbitTemplate createRabbitTemplate(ConnectionFactory connectionFactory){        RabbitTemplate rabbitTemplate=new RabbitTemplate();        rabbitTemplate.setConnectionFactory(connectionFactory);        rabbitTemplate.setMessageConverter(jackson2JsonMessageConverter());        return  rabbitTemplate;    }    @Bean    public Jackson2JsonMessageConverter jackson2JsonMessageConverter(){        return new Jackson2JsonMessageConverter();    }}
 测试:

RabbitMQ队列延迟

相关推荐