RABBITMQ fifth: 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.port}" 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= " Spittle.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= "spit Tle.fanout "durable=" true "> <rabbit:bindings> <rabbit:binding queue=" spittle.alert.queue.1 "&            gt;</rabbit:binding> <rabbit:binding queue= "spittle.alert.queue.2" ></rabbit:binding> <rabbit:binding queue= "spittle.alert.queue.3" ></rabbit:binding> </rabbit:bindings> </rab Bit:fanout-exchange>

Two: Configuration Generator

<import resource= "amqp-share.xml"/>    <!--create A Message Queuing template--    <rabbit:template id= " Rabbittemplate "connection-factory=" connectionfactory "                     Exchange=" spittle.fanout "message-converter= "jsonmessageconverter" >    </rabbit:template>    class= " Org.springframework.amqp.support.converter.JsonMessageConverter "></bean>

Iii: producer Procedures

 public classSpittleImplementsSerializable {PrivateLong id; PrivateSpitter spitter; PrivateString message; PrivateDate postedtime;  publicspittle (Long id, spitter spitter, String message, Date Postedtime) { this. ID =id;  this. Spitter =spitter;  this. Message =message;  this. Postedtime =postedtime; }     publicLong getId () {return  this. id; }     publicString getMessage () {return  this. message; }     publicDate getpostedtime () {return  this. postedtime; }     publicspitter getspitter () {return  this. spitter; }}
 public classProducermain { public Static voidMain (string[] Args)throwsException {applicationcontext Context=NewClasspathxmlapplicationcontext ("amqp/amqp-producer.xml"); Amqptemplate Template= (amqptemplate) Context.getbean ("rabbittemplate");  for(inti = 0; I < 20; i++) {System.out.println ("sending message #" +i); Spittle spittle=NewSpittle ((LongINULL, "Hello world" ("+ i +") ",NewDate ());            Template.convertandsend (spittle); Thread.Sleep (5000); } 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/  */ public  class  spittlealerthandler  MessageListener {@Override  public  void< /span> onMessage (message message) { try " Span style= "color: #000000;" > {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>    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 {    publicstaticvoid  main (string[] Args) {        New classpathxmlapplicationcontext ("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, which means 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 Exch ange= "${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 fifth: 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.