RabbitMQ 延遲任務(限時訂單) 原理 以及代碼 實戰

  • 1、場景

    咱們常常會遇見,一個需求就是,發送一條指令(消息),延遲一段時間執行,好比說常見的淘寶當下了一個訂單後,訂單支付時間爲半個小時,若是半個小時沒有支付,則關閉該訂單。固然實現的方式有幾種,今天來看看rabbitMQ實現的方式。

java

  • 2、思路:rabbitMQ 如何實現 

  1. rabbitMQ爲每一個隊列設置消息的超時時間只要給隊列設置x-message-ttl 參數,就設定了該隊列全部消息的存活時間,時間單位是毫秒。若是聲明隊列時指定了死信交換器則過時消息會成爲死信消息
  2. 須要設置的參數爲:ide

  • 3、原理:上圖

  1. 將延遲隊列(queue)在聲明的時候設置參數 「 x-dead-letter-exchange 」,「 x-message-ttl 「 分別對應 死信路由器(dlx_exchange) 和 消息過時時間(好比說30分鐘)。ui

  2.  一個消息從生產者發送到延遲隊列 ,在延遲隊列裏等待,等待30分鐘後,會去綁定的死信路由(dlx_exchange)。經過死信路由的規則,走到死信隊列。spa

  3. 這時候監聽死信隊列的消費者就能夠接收到消息,消費消息。好比說查看該訂單是否支付,若是沒有支付,則關閉該訂單。
  • 4、代碼實戰

  1. 生產者代碼:
    import com.dbg.example.connectionFactory.RQconnFactory;
    import com.rabbitmq.client.BuiltinExchangeType;
    import com.rabbitmq.client.Channel;
    import com.rabbitmq.client.Connection;
    import com.rabbitmq.client.ConnectionFactory;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    import java.util.concurrent.TimeoutException;
    
    
    public class DelayProducer {
    
            public static Logger logger = LoggerFactory.getLogger(DelayProducer.class);
    
            // 交換機
            public static final String exchangeName = "delay_Task";
            // 聲明路由鍵
            public static final String routekey = "delay_order";
    
            public static void  pend (List<String> orderNos) throws IOException, TimeoutException {
    
                    // 經過單例獲得工廠
                    ConnectionFactory connectionFactory = RQconnFactory.getrQconnFactory();
                    Connection connection = connectionFactory.newConnection();
                    final Channel channel = connection.createChannel();
    
                    // 聲明一個交換機
                    channel.exchangeDeclare(exchangeName , BuiltinExchangeType.DIRECT);
    
                    // 消息綁定
                    for (String orderNo :orderNos ) {
                        channel.basicPublish(exchangeName , routekey , null ,orderNo.getBytes());
                        logger.info("發送訂單 : "+ orderNo);
                    }
                    // 關閉頻道和鏈接
                    channel.close();
                    connection.close();
            }
    
            public static void main(String[] args) {
                    List orders = new ArrayList();
                    orders.add("order 0001");
                    orders.add("order 0002");
                    orders.add("order 0003");
                    try {
                            pend(orders);
                    } catch (IOException e) {
                            e.printStackTrace();
                    } catch (TimeoutException e) {
                            e.printStackTrace();
                    }
            }
    
    
    }

     

  2. 消費者代碼:
    import com.dbg.example.connectionFactory.RQconnFactory;
    import com.rabbitmq.client.*;
    
    import java.io.IOException;
    import java.util.HashMap;
    import java.util.Map;
    import java.util.concurrent.TimeoutException;
    
    
    public class DelayConsumer {
    
        public static void receive() throws IOException, TimeoutException {
    
            // 經過單例獲得工廠
            ConnectionFactory connectionFactory = RQconnFactory.getrQconnFactory();
            Connection connection = connectionFactory.newConnection();
            final Channel channel = connection.createChannel();
    
            // 聲明一個死信路由
            String dlxExchangeName = "dlx_delay";
            channel.exchangeDeclare(dlxExchangeName , BuiltinExchangeType.TOPIC);
            // 聲明一個死信訂單隊列
            String dlxQueueName = "dlx_delay_order";
            channel.queueDeclare( dlxQueueName ,true , true ,false ,null);
            // 綁定
            channel.queueBind(dlxQueueName , dlxExchangeName , "#");
    
            // 聲明一個交換機
            channel.exchangeDeclare(DelayProducer.exchangeName , BuiltinExchangeType.DIRECT);
            // 聲明一個延遲訂單隊列 ,並綁定死信路由器
            String queueName = "delay_order";
            Map<String ,Object> arguments = new HashMap<>();
            arguments.put("x-dead-letter-exchange",dlxExchangeName);
            arguments.put("x-message-ttl", 5 * 1000);  // 5秒過時時間
            channel.queueDeclare(queueName,true , false ,false , arguments );
            // 綁定
            channel.queueBind(queueName , DelayProducer.exchangeName ,DelayProducer.routekey);
    
            // 聲明一個消費者(關閉爲支付訂單的服務)
            final Consumer consumer = new DefaultConsumer(channel){
                @Override
                public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                                           byte[] body) throws IOException {
                    String message = new String(body, "UTF-8");
                    System.out.println("Received and close [" +envelope.getRoutingKey() +"]"+message);
                }
            };
    
            // 消費者消費--隊列()
            channel.basicConsume(dlxQueueName,true , consumer);
    
        }
    
    
        public static void main(String[] args) {
            try {
                receive();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (TimeoutException e) {
                e.printStackTrace();
            }
        }
    
    }

    3.獲得單例鏈接工廠code

    public class RQconnFactory {
    
        private volatile static ConnectionFactory rQconnFactory;
    
        private RQconnFactory(){
            
        }
    
        public static ConnectionFactory getrQconnFactory() {
            if (rQconnFactory == null) {
                synchronized (RQconnFactory.class){
                    if (rQconnFactory  == null ){
                        rQconnFactory = new ConnectionFactory();
                        rQconnFactory.setHost("192.168.31.220");
                        return rQconnFactory;
                    }
                }
            }
            return rQconnFactory;
        }
    }
相關文章
相關標籤/搜索