Message Queuing RABBITMQ integration with spring

Source: Internet
Author: User

1.RabbitMQ Introduction

RABBITMQ is a popular open source Message Queuing system, developed in Erlang language. RABBITMQ is the standard implementation of the AMQP (Advanced Message Queuing protocol).
Official website: http://www.rabbitmq.com/

2.Spring Integrated RabbitMQ2.1 maven Configuration
// pom.xml<dependency>      <groupId>com.rabbitmq</groupId>      <artifactId> amqp-client</artifactid>      <version>3.5.1</version>    </dependency>    < dependency>        <groupId>org.springframework.amqp</groupId>        <artifactid>spring-rabbit </artifactId>        <version>1.4.5.RELEASE</version>    </dependency>
2.2 RABBMITMQ configuration file
// rabbitmq-config.propertiesmq.host=127.0.0.1mq.username=Testmq.password=123456  Mq.port=5672mq.vhost=TESTMQ
2.3 Spring Configuration
//Application-mq.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://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsdhttp//Www.springframework.org/schema/rabbithttp//www.springframework.org/schema/rabbit/spring-rabbit-1.0.xsd ">&LT;DESCRIPTION&GT;RABBITMQ Connection Service Configuration </description> <!--connection configuration-<rabbit:connection-factory id= "Connect Ionfactory "host=" ${mq.host} "Username=" ${mq.username} "password=" ${mq.password} "port=" ${mq.port} "virtual-host=" $ {mq.vhost} "/> <rabbit:admin connection-factory=" ConnectionFactory "/> <!--spring Template declaration--&lt  ; rabbit:template exchange= "Amqpexchange" id= "Amqptemplate" connection-factory= "ConnectionFactory" message-converter= "Jsonmessageconverter"/> <!--Message Object JSON conversion class--<bean id= "Jsonmessageconverter"class= "Org.springframework.amqp.support.converter.Jackson2JsonMessageConverter"/> </beans>
3. Use RabbitMQ3.1 in spring to declare a Message Queuing queue
// application-mq.xml<rabbit:queue id= "Test_queue_key" name= "Test_queue_key" durable= "true" auto-delete= " False "exclusive=" false "/>

Description
Durable: whether to persist
Exclusive: Only private queues that the creator can use, automatically deleted after disconnection
Auto_delete: Automatically delete queues when all consumer client connections are disconnected

3.2 Switch Definition
// application-mq.xml<rabbit:direct-exchange name= "Test-mq-exchange" durable= "true" auto-delete= "false" Id= "Test-mq-exchange" >    <rabbit:bindings>        <rabbit:binding queue= "Test_queue_key" key= "Test_ Queue_key "/>    </rabbit:bindings></rabbit:direct-exchange>

Description
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

3.3 Sending a message producer
// Mqproducer.java  Public Interface mqproducer {    /**     * Sends a message to the     specified queue @param  queuekey      @param Object      */     Public void Senddatatoqueue (String Queuekey, Object object);}
@Service Public classMqproducerimplImplementsMqproducer {@AutowiredPrivateamqptemplate amqptemplate; Private Final StaticLogger Logger = Logger.getlogger (Mqproducerimpl.class); /*(non-javadoc) * @see com.stnts.tita.rm.api.mq.mqproducer#senddatatoqueue (java.lang.String, Java.lang.Object) */@Override Public voidSenddatatoqueue (String Queuekey, Object object) {Try{amqptemplate.convertandsend (Queuekey, object); } Catch(Exception e) {logger.error (e); }    }}

Description
Convertandsend: Converting a Java object to a message sent to a switch that matches key exchange, where JSON conversion is configured, this is the form of converting a Java object into a JSON string.

Original: Convert a Java object to an AMQP Message and send it to a default exchange with a specific routing key.

3.4 Receiving Messages asynchronously consumer

Defining listeners

// Queuelistenter.java @Component  Public class Implements MessageListener {    @Override    publicvoid  onMessage (Message msg) {         try{            System.out.print (msg.tostring ());        } Catch (Exception e) {            e.printstacktrace ();     }}}

Monitoring Configuration

// application-mq.xml<rabbit:listener-container connection-factory= "ConnectionFactory" acknowledge= " Auto ">    <rabbit:listener queues=" Test_queue_key "ref=" Queuelistenter "/></rabbit: Listener-container>

Description
Queues: Listener queue, multiple words separated by commas (,)
Ref: Listener

3.5 JUnit Test
//Testqueue.java@RunWith (value = Springjunit4classrunner.class) @ContextConfiguration (Locations= {    "Classpath:/applicationcontext/applicationcontext-mq.xml"}) Public classtestqueue{@Autowired mqproducer mqproducer; FinalString Queue_key = "Test_queue_key"; @Test Public voidSend () {Map<String,Object> msg =NewHashMap () <>; Msg.put ("Data", "hello,rabbmitmq!");    Mqproducer.senddatatoqueue (QUERY_KEY,MSG); }}

Running the test program, run with JUnit, sends a message to Test_queue, which, after the listener hears the message, prints the message.

At this point, the spring and RABBMITMQ integration, configuration, and use have been completed.

Message Queuing RABBITMQ integration with spring

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.