Spring boot rabbitMQ delay queue implementation

Spring boot uses rabbitMQ
to import related dependencies as follows:

 

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

AMQP is implemented as rabbitMQ by default.

 

In order to customize the configuration, the automatic configuration of boot is abandoned. So, the following is the configuration file of RabbitMQ:

 

package com.fengbaogu.config;

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.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Configuration class for rabbitmq
 * @author LiaoLe
 */
@Configuration
public class RabbitMQConfig {
    /** The name of the message exchange */
    public static final String EXCHANGE = "delayed_exchange";
    /** queue key1*/
    public static final String ROUTING = "notify";
    /** Queue name */
    public static final String QUEUE = "delayed_queue";
    /** rabbit MQ account */
    public static final String USERNAME = "liaoke";
    /**rabbit MQ password*/
    public static final String PASSWORD = "198461lk";
    /**rabbit MQ address*/
    public static final String RABBITMQ_ADDRESS="localhost";
    /**rabbit MQ port*/
    public static final Integer RABBITMQ_PORT=5672;

    /**
     * Configuration link
     * @return
     */
    @Bean
    public ConnectionFactory connectionFactory() {
        CachingConnectionFactory connectionFactory = new CachingConnectionFactory(RABBITMQ_ADDRESS,RABBITMQ_PORT);
        connectionFactory.setUsername(USERNAME);
        connectionFactory.setPassword(PASSWORD);
        connectionFactory.setVirtualHost("/");
        connectionFactory.setPublisherConfirms(true); /**Need to set accept callback information*/
        return connectionFactory;
    }


    /**
     * Switch settings
     * Turn on delayed messages
     * @return
     */
    @Bean
    public DirectExchange defaultExchange() {
        DirectExchange directExchange = new DirectExchange(EXCHANGE, true, false);
        directExchange.setDelayed(true);/**Just one simple step to open the delayed message, md has been looking for a long time, it turns out that it is so simple*/
        return directExchange;
    }

    /**
     * Queue settings
     * @return
     */
    @Bean
    public Queue notifyQueue() {
        return new Queue(QUEUE,true);/**Message persistence*/
    }

    /**
     * Bind the queue to the exchange
     * @return
     */
    @Bean
    public Binding bindingNotify() {
        return BindingBuilder.bind(notifyQueue()).to(defaultExchange()).with(ROUTING);
    }

}

 RabbitMQ does not turn on the delayed function by default, so students also need to download the plug-in from the official website or github:

 

命令行: rabbitmq-plugins enable rabbitmq_delayed_message_exchange
 

#Install plugin https://github.com/rabbitmq/rabbitmq-delayed-message-exchange 

 

#The plugin has version requirements

 

The code sent below is pasted, and an http entry is used casually:

package com.fengbaogu.web;

import com.fengbaogu.config.RabbitMQConfig;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.support.CorrelationData;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

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

/**
 * Created by LiaoKe on 2017/5/2.
 */
@RestController
public class TestController implements RabbitTemplate.ConfirmCallback{


    /**
     * Send messages using RabbitTemplate
     */
    private RabbitTemplate rabbitTemplate;

    /**
     * Construction method
     * @param rabbitTemplate
     */
    public TestController(RabbitTemplate rabbitTemplate){
        this.rabbitTemplate = rabbitTemplate;
        //Set the consumer callback
        this.rabbitTemplate.setConfirmCallback(this);
    }

    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


    /**
     * Send a message to the delay queue
     * @param msg
     * @return
     */
    @RequestMapping("send")
    public String send3(String msg){
        String uuid = UUID.randomUUID().toString();
        CorrelationData correlationId = new CorrelationData(uuid);
        rabbitTemplate.convertAndSend(RabbitMQConfig.EXCHANGE,RabbitMQConfig.ROUTING , msg, new MessagePostProcessor() {
                    @Override
                    public Message postProcessMessage(Message message) throws AmqpException {
                        message.getMessageProperties().setDelay(20000);/**Delay 20 seconds to send*/
                        message.getMessageProperties().setDeliveryMode(MessageDeliveryMode.PERSISTENT);/**消息持久化*/
                        System.out.println(sdf.format(new Date()) + " Delay sent.");
                        return message;
                    }
                }, correlationId);
        return null;
    }

    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
        System.out.println(" 回调id:" + correlationData);
        if (ack) {
            System.out.println("Message successfully consumed");
        } else {
            System.out.println("Message consumption failed:" + cause+"\nResend");
        }
    }
}

 

 

After startup, you can have the following on the RabbitMQ management interface:



 such a switch.

Queue can also be seen on the management interface in the same way, and there is no map here.

 

Now look at the Consumer side, the code is very concise:

package com.fengbaogu.listener;

import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.util.Date;


/**
 * Created by LiaoKe on 2017/5/3.
 */
@Component
@RabbitListener(queues = {"delayed_queue"})
public class Receiver {


    @RabbitHandler
    public void process(String msg)  {
        System.out.println("start one work and now data:"+new Date().toString());
        System.out.println("This msg is:"+msg);
    }



}

Open the consumer and access the send entry:

Server prints:

2017-05-03 20:24:14 Delay sent.

 Callback id: CorrelationData [id=277ce017-af15-4571-b556-762fec62720d]

Message successfully consumed

Consumer print:

start one work and now data:Wed May 03 20:24:34 CST 2017

This msg is: I am message 2

 

So, a difference of 20 seconds. Delay queue Over.

 

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326473064&siteId=291194637