Spring boot RABBITMQ integration, delay Message Queuing implementation

Source: Internet
Author: User
Tags bind constant message queue wrapper rabbitmq

This article mainly records Spring boot integration rabbitmq, divided into two parts, the first part is to create a normal message queue, the second part of the delay message Queue implementation:

Spring boot provides support for AMQP-related packets for MQ Message Queuing, which can be introduced:

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

Property Profile Application.properties:

#rabbitmq  
spring.rabbitmq.host=127.0.0.1  
spring.rabbitmq.port=5672  
spring.rabbitmq.username=root  
Spring.rabbitmq.password=root  

RABBITMQ configuration classes, configuring connection factories and manipulating objects:

@Configuration @ConfigurationProperties (prefix = "SPRING.RABBITMQ") public class Rabbitmqconfiguration {privat  

    e static Logger Logger = Logger.getlogger (Rabbitmqconfiguration.class);  

    Private String host;  

    private int port;  

    Private String username;  

    private String password; Link Information @Bean public connectionfactory connectionfactory () {cachingconnectionfactory connectionfact  
        Ory = new Cachingconnectionfactory (host, Port);  
        Connectionfactory.setusername (username);  
        Connectionfactory.setpassword (password);  
        Connectionfactory.setvirtualhost ("/");  
        Connectionfactory.setpublisherconfirms (TRUE);  
        Logger.info ("Create connectionfactory Bean..");  
    return connectionfactory;  
        } @Bean @Scope (configurablebeanfactory.scope_prototype) public rabbittemplate rabbittemplate () {  
        Rabbittemplate template = new Rabbittemplate (ConnectionFactory ()); REturn template;   }//Omit getter Setter}

Define the service interface as follows:
Temporarily regardless of delay queue, define Send message interface

/** 
 *  
 * @author Victor 
 * @desc Message Queuing Service Interface */public  
interface Imessagequeueservice {  

    /** 
     * Send message to queue 
     * @param queue queue name 
     * @param message content * * * public  
    void Send (String queuename,string message);  


}  

Service implementation

package com.ks.server.service.impl.queue;  
Import org.springframework.amqp.AmqpException;  
Import Org.springframework.amqp.core.Message;  
Import Org.springframework.amqp.core.MessagePostProcessor;  
Import Org.springframework.amqp.rabbit.core.RabbitTemplate;  
Import org.springframework.beans.factory.annotation.Autowired;  

Import Org.springframework.stereotype.Service;  
Import Com.base.common.codec.JSONUtils;  
Import com.ks.common.constant.MQConstant;  
Import Com.ks.common.service.queue.IMessageQueueService;  

Import Com.ks.modal.queue.DLXMessage; /** * * @author Victor * @desc Message Queuing Service Interface Implementation */@Service ("Messagequeueservice") public class Messagequeueservice  

    Impl implements imessagequeueservice{@Autowired private rabbittemplate rabbittemplate; @Override public void Send (string queuename, String msg) {Rabbittemplate.convertandsend (mqconstant.defaul  
    T_exchange,queuename, MSG); }  



}  

Related constant class:

Package com.ks.common.constant;  

/** 
 *  
 * @author Victor 
 * @desc Rabbit Message Queue Related constants */public  
final class Mqconstant {  

    private Mqconstant () {  
    }  

    //exchange name public  
    static final String Default_exchange = "Kshop";  

    DLX QUEUE public  
    static final String default_dead_letter_queue_name = "Kshop.dead.letter.queue";  

    DLX Repeat queue dead-letter forwarding queues public  
    static final String default_repeat_trade_queue_name = "Kshop.repeat.trade.queue";  


    //hello test Message queue name public  
    static final String hello_queue_name = "Hello";  


}  

So far, the queue-related configuration, as well as the use and encapsulation is complete, followed by the creation of queues,
Here I am. Create a configuration class for the queue configuration, and create a Hello queue example as follows:

Package com.ks.ons.config;  
Import Java.util.HashMap;  

Import Java.util.Map;  
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 com.ks.common.constant.MQConstant; /** * * @author Victor * @desc Queue Configuration */@Configuration public class Queueconfiguration {//Channel configuration @ Bean public Directexchange Defaultexchange () {return new Directexchange (Mqconstant.default_exchange, True  
    , false);  
        }/********************* Hello queue test *****************/@Bean public Queue queue () {  
        Queue queue = new Queue (mqconstant.hello_queue_name,true);   
    return queue; } @Bean Public Binding binding () {return BindingbuildeR.bind (Queue ()). to (Defaultexchange ()). with (Mqconstant.hello_queue_name);   }  

}

By configuring the queue bean, when the program starts, it creates the related queue in RABBITMQ, launches the program, and can see the channel and queue information in the RABBTMQ management interface:

As we all know, since there is a queue to handle the business of the end still need consumers, consumers create examples are as follows:

Package Com.ks.ons.processor.hello;  

Import Org.springframework.amqp.rabbit.annotation.RabbitHandler;  
Import Org.springframework.amqp.rabbit.annotation.RabbitListener;  
Import org.springframework.stereotype.Component;  

Import com.ks.common.constant.MQConstant;  

/** 
 *  
 * @author Victor 
 * @desc Hello Message Queuing consumer 
 *  
/@Component @RabbitListener (queues = Mqconstant.hello_queue_name) Public  
class Helloprocessor {  

    @RabbitHandler public  
    void Process (String Content) {  
        System.out.println ("Accept message:" + content);  
    }  
}  

Inject Service

@Autowired  
private Imessagequeueservice messagequeueservice;  

Send Message

Messagequeueservice.send (mqconstant.hello_queue_name, "Test send Message");  

Next show how to implement the delay queue, before this, if the reader like me on the RABBITMQ queue does not know the depth of the,–> recommendation article, you can RABBITMQ delay queue implementation ideas have a rough idea.
In this paper, the delivery delay queue is implemented mainly through the DLX feature of RABBITMQ:
Ideas are as follows:

Client: Refers to the specific message end to MQ, the client makes a custom wrapper for the message content, with the target queue name attached to the message. For example: The client sends the string "Hello" to the queue Q1, the delay time is 60 seconds, the wrapper is modified to {"QueueName": "Q1", "Body": "Hello"}, at this point, the message is sent to the DLX dead-letter queue instead of the Q1 queue, and the message is set to a 60-second timeout.

DLX: Dead-letter queue, which stores messages with time-out information, and can be set to forward to another specified queue when a message times out (this setting forwards to router), no consumer, when a client message is received, waits for the message to time out, forwards the message to the specified router queue

Router: A forwarding queue that receives a dead-letter queue timeout message, such as the example message, after it is received, the consumer resolves the message, gets the Queuename,body, and sends a message to the QueueName queue that gets the content body.

Q1,q2,q3.: User business queue, when Q1 receives Hello, it is 60 seconds after the consumption

Modify the code above, add two queues,
Dead-letter queue: Store delayed messages sent,
Routing forward queue: used to accept dead-letter messages for death and forward messages to the business destination queue
The code after the modification is as follows:

/** * * @author Victor * @desc Queue Configuration */@Configuration public class Queueconfiguration {//Channel configuration @ Bean public Directexchange Defaultexchange () {return new Directexchange (Mqconstant.default_exchange, True  
    , false); } @Bean Public Queue Repeattradequeue () {Queue queue = new Queue (Mqconstant.default_repeat_trade_  
        Queue_name,true,false,false);   
    return queue; } @Bean Public Binding drepeattradebinding () {return Bindingbuilder.bind (Repeattradequeue ()). to (d  
    Efaultexchange ()). with (Mqconstant.default_repeat_trade_queue_name); } @Bean Public Queue deadletterqueue () {map<string, object> arguments = new Hashmap<> (  
        );  
        Arguments.put ("X-dead-letter-exchange", Mqconstant.default_exchange);  
        Arguments.put ("X-dead-letter-routing-key", mqconstant.default_repeat_trade_queue_name); Queue queue = new Queue (Mqconstant.default_dead_letter_queue_name,true,false,false,arguments);  
        System.out.println ("arguments:" + queue.getarguments ());   
    return queue; } @Bean Public Binding deadletterbinding () {return Bindingbuilder.bind (Deadletterqueue ()). to (DEFA  
    Ultexchange ()). with (Mqconstant.default_dead_letter_queue_name);  
        }/********************* Hello queue test *****************/@Bean public Queue queue () {  
        Queue queue = new Queue (mqconstant.hello_queue_name,true);   
    return queue; } @Bean Public Binding binding () {return Bindingbuilder.bind (Queue ()). to (Defaultexchange ()). with (M  
    Qconstant.hello_queue_name);   }  

}

Modify Service services:

Package com.ks.common.service.queue;  


/** 
 *  
 * @author Victor 
 * @desc Message Queuing Service Interface */public  
interface Imessagequeueservice {  

    /** 
     * Send message to queue 
     * @param queue queue name 
     * @param message content * * * public  
    void Send (String queuename,string message) ;  

    /** 
     * Delay sending message to queue 
     * @param queue queue name 
     * @param message message content 
     * @param times delay Unit milliseconds * 
     /  
    Publi c void Send (String queuename,string message,long times);  
}  
Package com.ks.server.service.impl.queue;  
Import org.springframework.amqp.AmqpException;  
Import Org.springframework.amqp.core.Message;  
Import Org.springframework.amqp.core.MessagePostProcessor;  
Import Org.springframework.amqp.rabbit.core.RabbitTemplate;  
Import org.springframework.beans.factory.annotation.Autowired;  

Import Org.springframework.stereotype.Service;  
Import Com.base.common.codec.JSONUtils;  
Import com.ks.common.constant.MQConstant;  
Import Com.ks.common.service.queue.IMessageQueueService;  

Import Com.ks.modal.queue.DLXMessage; /** * * @author Victor * @desc Message Queuing Service Interface Implementation */@Service ("Messagequeueservice") public class Messagequeueservice  

    Impl implements imessagequeueservice{@Autowired private rabbittemplate rabbittemplate; @Override public void Send (string queuename, String msg) {Rabbittemplate.convertandsend (mqconstant.defaul  
    T_exchange,queuename, MSG); } @Override public void Send (String QueueName, String msg, long times) {Dlxmessage dlxmessage = new Dlxmessage (queuename,msg,times); Messagepostprocessor processor = new Messagepostprocessor () {@Override public Message Postproc Essmessage (Message message) throws Amqpexception {message.getmessageproperties (). SetExpiration (Times +  
                "");  
            return message;  
        }  
        };  
        Dlxmessage.setexchange (Mqconstant.default_exchange); Rabbittemplate.convertandsend (Mqconstant.default_exchange,mqconstant.default_dead_letter_queue_name,  
    Jsonutils.tojson (Dlxmessage), processor);   }  


}

Jsonutils as a JSON tool class

New message entity for wrapping messages:

Package com.ks.modal.queue;  

Import java.io.Serializable;  

/** 
 *  
 * @author Victor 
 * @desc Rabbit Dead Letter Message carrier */public  
class Dlxmessage implements Serializable {
  private static final Long serialversionuid = 9956432152000L;  

    Public Dlxmessage () {  
        super ();  
    }  

    Public Dlxmessage (String queuename, string content, long times) {  
        super ();  
        This.queuename = queuename;  
        this.content = content;  
        This.times = times;  
    }  

    Public Dlxmessage (String Exchange, String queuename, string content, long times) {  
        super ();  
        This.exchange = Exchange;  
        This.queuename = queuename;  
        this.content = content;  
        This.times = times;  
    }  


    Private String exchange;  

    Private String queuename;  

    Private String content;  

    Private long times;  

    Omit Getter Setter  

}  

Routing Forward Queue consumer implementation, responsible for receiving timeout messages, forwarding:

package Com.ks.ons.processor.system;  
Import Org.springframework.amqp.rabbit.annotation.RabbitHandler;  
Import Org.springframework.amqp.rabbit.annotation.RabbitListener;  
Import org.springframework.beans.factory.annotation.Autowired;  

Import org.springframework.stereotype.Component;  
Import Com.base.common.codec.JSONUtils;  
Import com.ks.common.constant.MQConstant;  
Import Com.ks.common.service.queue.IMessageQueueService;  

Import Com.ks.modal.queue.DLXMessage; /** * * @author Victor * @desc dead Letter Receive processing consumer */@Component @RabbitListener (queues = Mqconstant.default_repeat_tra  

    De_queue_name) public class TradeProcessor {@Autowired private imessagequeueservice messagequeueservice; @RabbitHandler public void process (String content) {Dlxmessage message = Jsonutils.tobean (content,  
        Dlxmessage.class);  
    Messagequeueservice.send (Message.getqueuename (), message.getcontent ()); }  
}  

After starting the project, the administration interface is as follows:

To test the code snippet:

Messagequeueservice.send (mqconstant.hello_queue_name, "Test delay sending message", 60000);  

Transferred from: http://blog.csdn.net/i_vic/article/details/72742277

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.