RABBITMQ Fourth: Spring Integrated RABBITMQ

Source: Internet
Author: User
Tags message queue rabbitmq

A few of the previous tutorials explain how to use RABBITMQ, which focuses on spring integrated RABBITMQ.

First introduce the configuration file Org.springframework.amqp, as follows

        <dependency>            <groupId>org.springframework.amqp</groupId>            <artifactId> spring-rabbit</artifactid>            <version>1.6.0.RELEASE</version>        </dependency>
One: Configure the consumer and Generator public section
<rabbit:connection-factory id= "ConnectionFactory" host= "${rabbit.hosts}" port= "${RABBIT.P                               ORT} "Username=" ${rabbit.username} "password=" ${rabbit.password} "virtual-host=" ${rabbit.virtualhost} " Channel-cache-size= "/> <rabbit:admin connection-factory=" ConnectionFactory "/> <!--define Message Queuing-- > <rabbit:queue name= "spittle.alert.queue.1" durable= "true" auto-delete= "false"/> <rabbit:queue name= "sp Ittle.alert.queue.2 "durable=" true "auto-delete=" false "/> <rabbit:queue name=" spittle.alert.queue.3 "durable= "True" auto-delete= "false"/> <!--bound Queue--<rabbit:fanout-exchange id= "Spittle.fanout" Name= "Spittle.fano UT "durable=" true "> <rabbit:bindings> <rabbit:binding queue=" Spittle.alert.queue.1 "></ rabbit:binding> <rabbit:binding queue= "spittle.alert.queue.2" ></rabbit:binding> <r Abbit:binding queue= "spittle.Alert.queue.3 "></rabbit:binding> </rabbit:bindings> </rabbit:fanout-exchange> 

Two: Configuration generator

<import resource= "Amqp-share.xml"/>    <!--creating a Message Queuing template--    <rabbit:template id= "Rabbittemplate" connection-factory= "ConnectionFactory"                     exchange= "Spittle.fanout" message-converter= "JsonMessageConverter" >    </rabbit:template>    <bean id= "Jsonmessageconverter" class= " Org.springframework.amqp.support.converter.JsonMessageConverter "></bean>

III: Producer Procedures

public class Spittle implements Serializable {    private Long ID;    Private Spitter spitter;    private String message;    Private Date postedtime;    Public spittle (Long ID, spitter spitter, String message, Date postedtime) {        this.id = ID;        This.spitter = Spitter;        this.message = message;        This.postedtime = Postedtime;    }    Public Long getId () {        return this.id;    }    Public String GetMessage () {        return this.message;    }    Public Date Getpostedtime () {        return this.postedtime;    }    Public Spitter Getspitter () {        return this.spitter;    }}
public class Producermain {public    static void Main (string[] args) throws Exception {        ApplicationContext context = New Classpathxmlapplicationcontext ("Amqp/amqp-producer.xml");        Amqptemplate template = (amqptemplate) context.getbean ("Rabbittemplate");        for (int i = 0; i <; i++) {            System.out.println ("Sending message #" + i);            Spittle spittle = new Spittle ((long) I, NULL, "Hello World (" + i + ")", New Date ());            Template.convertandsend (spittle);            Thread.Sleep ();        }        System.out.println ("done!");}    }

Where the Convertandsend method defaults to the first parameter is the switch name, the second parameter is the route name, the third is the data we send, now we start the program, the effect is as follows

Fourth one: Consumer programs

First write a code to listen to the producer sending the message

/** * Created by Administrator on 2016/11/18. */public class Spittlealerthandler implements MessageListener {    @Override public    void OnMessage (Message message) {        try {            string body=new string (Message.getbody (), "UTF-8");            System.out.println (body);        } catch (Unsupportedencodingexception e) {            e.printstacktrace ();}}    }

Be careful to implement MessageListener, we just need to get the body of the message, we can use JSON to transform the program we need (for example, we can send a map,map to store methods and entities so that we could invoke different programs to run through reflection).

Below we configure the consumer

<import resource= "Amqp-share.xml"/>    <rabbit:listener-container connection-factory= " ConnectionFactory ">      <rabbit:listener ref=" Spittlelistener "method=" OnMessage "queues=" Spittle.alert.queue.1,spittle.alert.queue.3,spittle.alert.queue.2 "/>    </rabbit:listener-container>    <bean id= "Spittlelistener" class= "Com.lp.summary.rabbitmq.impl.SpittleAlertHandler"/>

Where Spittlelistener is a listening program, method is the way to execute, queues is the queue we listen to, multiple queues can be separated by commas (because we are using distribution, so three queues get the same message, here for the sake of simplicity I put in a listener, In fact, we can write three consumers, each listening to a queue of consumers

Now you just need to start the program to run

public class Consumermain {public    static void Main (string[] args) {        ApplicationContext context = new Classpathxml ApplicationContext ("Amqp/amqp-consumer.xml");}    }

Of course, direct is similar to the above, except that this is based on routing matching, first send the data to the switch, then bind the route and queue, through the switch ID and route to find the queue, the following are some of the main configuration

 <rabbit:queue id= "Spring-test-queue1" durable= "true" auto-delete= "false" Exclusive= "false" Name= " Spring-test-queue1 "></rabbit:queue> <rabbit:queue name=" Spring-test-queue2 "durable=" true "Auto-delete = "false" Exclusive= "false" ></rabbit:queue> <!--switch definition--<!--rabbit:        Direct-exchange: Defines the Exchange Mode as direct, meaning that the message is not forwarded until it exactly matches a specific routing key. Rabbit:binding: Set Message queue matching key--> <rabbit:direct-exchange name= "${rabbit.exchange.direct}" durable= "true" Auto-delete= "false" Id= "${rabbit.exchange.direct}" > <rabbit:bindings> <rabbit:binding queue= "Spring-test-queue1" key= "Spring.test.queueKey1"/> <rabbit:binding queue= "spring-test-queue2" key= "Spring    . Test.queuekey2 "/> </rabbit:bindings> </rabbit:direct-exchange> <!--spring Template declaration-- <rabbit:template exchange= "${rabbit.exchange.direct}" id= "Rabbittemplate" connection-factory= " ConnectionFactory "Message-convErter= "Jsonmessageconverter" ></rabbit:template> <!--message objects into json--> <bean id= " Jsonmessageconverter "class=" Org.springframework.amqp.support.converter.JsonMessageConverter "></bean>

Here is the consumer monitoring configuration

<rabbit:listener-container connection-factory= "connectionfactory" acknowledge= "Auto" >        <rabbit: Listener queues= "spring-test-queue1" method= "OnMessage" ref= "Queuelistenter" ></rabbit:listener>    < /rabbit:listener-container>    <rabbit:listener-container connection-factory= "ConnectionFactory" acknowledge= "Auto" >        <rabbit:listener queues= "spring-test-queue2" method= "OnMessage" ref= "Queuelistenter "></rabbit:listener>    </rabbit:listener-container>

Here is the program

public static void Main (string[] args) {        applicationcontext context=new classpathxmlapplicationcontext (" Applicationcontext-rabbitmq-producer.xml ");        Mqproducer mqproducer= (mqproducer) Context.getbean ("Mqproducer");        Mqproducer.senddatetoqueue ("Spring.test.queueKey1", "Hello World Spring.test.queueKey1");        Mqproducer.senddatetoqueue ("Spring.test.queueKey2", "Hello World Spring.test.queueKey2");    

The actual situation may require us to separate the consumer and generator programs. Of course, spring also has a load-balanced configuration, which is not much introduced here.

RABBITMQ Fourth: Spring Integrated RABBITMQ

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.