Spring MVC Consolidation RABBITMQ Implementation delay Queue __RABBITMQ

Source: Internet
Author: User
Tags rabbitmq

This is an example of a spring MVC consolidation RABBITMQ Implementation delay queue that contains the complete code that can be run. have been groping for a long time before, hope can help you to take some detours less. Starting in Shen's blog. What is a deferred queue

In layman's parlance, the delay queue is a bit like the timer used in our lives, the timer will ring after the specified time, and the deferred queue will process the message after the specified time. The main scenarios of delay queue are cancellation of order timeout, automatic evaluation of timeout and so on. Implementation Principle

RABBITMQ gives us both the TTL (time-to-live) and DLX (Dead-letter-exchange) features that are used by the RABBITMQ to implement deferred queues. The TTL is used to control the lifetime of a message and, if timed out, the message becomes dead letter. DLX is used to configure dead-letter queues, you can configure the X-dead-letter-exchange and X-dead-letter-routing-key parameters to specify the switches and queues that a message needs to be routed to after it becomes a dead letter. A detailed introduction to the TTL (time-to-live) and DLX (Dead-letter-exchange) can refer to the reference link at the end of the article. code Example

Briefly, the project first introduces the RABBITMQ dependent dependencies of spring, then configures a regular queue (Delay_queue) and a dead-letter queue (Task_queue) in Spring-rabbitmq.xml. Parameters such as X-message-ttl and X-dead-letter-exchange are configured on a regular queue to point to dead-letter queues. Finally, the task processor (DELAYTASK) is configured and the task processor is bound to the dead-letter queue and configured on the listener. Then you can happily implement the business logic ~

There are two service,producerservice and Consumerservice in the project, and you can run the main method of these two classes directly after you import the project to see the effect of the deferred queue. You can also run the Web project to test after you deploy to the local server, but only the producerservice is used in the test. Pom.xml

<?xml version= "1.0" encoding= "UTF-8"?> <project xmlns= "http://maven.apache.org/POM/4.0.0" xmlns:xsi= "HTT" P://www.w3.org/2001/xmlschema-instance "xsi:schemalocation=" http://maven.apache.org/POM/4.0.0 Http://maven.apach E.org/xsd/maven-4.0.0.xsd "> <modelVersion>4.0.0</modelVersion> <packaging>war</packaging > <groupId>com.shenofusc</groupId> <artifactid>spring-rabbitmq-delay-queue</artifactid&
    Gt <version>1.0-SNAPSHOT</version> <dependencies> <dependency> &LT;GROUPID&G T;org.springframework</groupid> <artifactId>spring-webmvc</artifactId> <versi on>4.3.7.release</version> </dependency> <dependency> <groupid>org .springframework</groupid> <artifactId>spring-context-support</artifactId> <v Ersion>4.3.7.release</version> </dependency> <dependency> <groupid>javax.servlet</gro Upid> <artifactId>javax.servlet-api</artifactId> &LT;VERSION&GT;4.0.0&LT;/VERSION&G
            T <scope>provided</scope> </dependency> <!--rabbitmq--> <dependency&gt
            ;
            <groupId>org.springframework.amqp</groupId> <artifactId>spring-amqp</artifactId> <version>2.0.0.RELEASE</version> </dependency> <dependency> &L
            T;groupid>org.springframework.amqp</groupid> <artifactId>spring-rabbit</artifactId> <version>2.0.0.RELEASE</version> </dependency> </dependencies> </project&gt ;
Spring-rabbitmq.xml
<beans xmlns= "Http://www.springframework.org/schema/beans" xmlns:xsi= "http://www.w3.org/2001/ Xmlschema-instance "xmlns:rabbit=" Http://www.springframework.org/schema/rabbit "xsi:schemalocation=" http://w
           Ww.springframework.org/schema/rabbit http://www.springframework.org/schema/rabbit/spring-rabbit.xsd

    Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd ">
        <bean id= "ConnectionFactory" class= "Org.springframework.amqp.rabbit.connection.CachingConnectionFactory" > <property name= "host" value= "localhost"/> <property name= "port" value= "5672"/> <property Name= "username" value= "Guest"/> <property name= "password" value= "Guest"/> </bean> <rabb
        It:admin connection-factory= "ConnectionFactory"/> <rabbit:queue name= "Delay_queue" auto-declare= "true" >
        <rabbit:queue-arguments>    <entry key= "X-message-ttl" value= "5000" value-type= "Java.lang.Long"/> <entry "key=" x-dead-letter-
        Exchange "value=" Exchange_delay "/> <entry key=" X-dead-letter-routing-key "value=" Task_queue "/> </rabbit:queue-arguments> </rabbit:queue> <rabbit:queue name= "Task_queue" auto-declare= "true"/
        > <rabbit:direct-exchange name= "Exchange_delay" durable= "false" Auto-delete= "false" id= "Exchange_delay" > <rabbit:bindings> <rabbit:binding queue= "Task_queue"/> </rabbit:bindings> & lt;/rabbit:direct-exchange> <rabbit:template id= "amqptemplate" connection-factory= "ConnectionFactory" queue= "Delay_queue" routing-key= "Delay_queue"/> <!--configuration thread pool--> <bean id = "Taskexecutor" class = "org.spring  Framework.scheduling.concurrent.ThreadPoolTaskExecutor "> <!--thread Pool maintains minimum number of threads--> <property name = "Corepoolsize" value = "5" /> <!--thread pool to maintain the idle time allowed by the thread--> <property name = "Keepaliveseconds" value = "30000"/> & lt;!
        --thread pool maintains the maximum number of threads--> <property name = "Maxpoolsize" value = "1000"/> < the buffer queue used by the thread pool--> <property name = "Queuecapacity" value = "/> </bean> <bean id=" Delaytask "class=" Com.sheno Fusc.task.DelayTask "/> <!--queue Listener notifies listeners on the corresponding queue when a message arrives--> <rabbit:listener-container Co nnection-factory= "ConnectionFactory" acknowledge= "Auto" task-executor= "Taskexecutor" > <rabbit:listener queue s= "Task_queue" ref= "Delaytask"/> </rabbit:listener-container> </beans>
Delaytask
public class Delaytask implements MessageListener {public
    void onMessage (Message message) {
        try {
            String rec eivedmsg = new String (Message.getbody (), "UTF-8");
            System.out.println ("Received:" + receivedmsg);
        } catch (Exception e) {
            e.printstacktrace ();}}}
Producerservice
@Service public
class Producerservice {

    @Resource
    private amqptemplate amqptemplate;

    public void Send (String msg) {
        amqptemplate.convertandsend (msg);
        System.out.println ("Sent:" + msg);
    }

    public static void Main (string[] args) {
        ApplicationContext context = new Genericxmlapplicationcontext ("classpath:/ Spring-rabbitmq.xml ");
        Amqptemplate amqptemplate = Context.getbean (amqptemplate.class);
        Amqptemplate.convertandsend ("Hello World");
        System.out.println ("Sent:hello World");
    }

Consumerservice
@Service public
class Consumerservice {

    @Resource
    private amqptemplate amqptemplate;

    public void recive () {
        System.out.println ("Received:" + Amqptemplate.receiveandconvert ());
    }

    public static void Main (string[] args) {
        ApplicationContext context = new Genericxmlapplicationcontext ("classpath:/ Spring-rabbitmq.xml ");
        Amqptemplate amqptemplate = Context.getbean (amqptemplate.class);
        System.out.println ("Received:" + Amqptemplate.receiveandconvert ());
    }

Complete Code

SPRING+RABBITMQ implementation Delay Queue considerations

After modifying the X-message-ttl parameter, the restart item will complain, delete the related queue can solve this problem, the system will automatically rebuild the queue when it starts. reference materials

Rabbitmq-time-to-live Extensions
Rabbitmq-dead Letter Exchanges
Spring-amqp with XML Configuration
S PRING-AMQP Sample Applications
RABBITMQ How to implement a deferred queue.
SPRING-AMQP Consolidation RABBITMQ Consumer configuration and code
Use dead Letter (dead-mail queue) for delayed delivery

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.