RABBITMQ Integrated spring boot Message Queue Starter Demo

Source: Internet
Author: User
Tags message queue rabbitmq


Spring Boot integrated RABBITMQ is also very handy. Now let's take a simple example to integrate RABBITMQ. Getting Started demo.

Key concepts:

Among the more important concepts are 4: Virtual hosts, switches, queues, and bindings.


Virtual Host: A virtual host holds a set of switches, queues, and bindings. Why do you need multiple virtual hosts? Very simple, RABBITMQ, the user can only be in the granularity of the virtual host permissions control. Therefore, if you need to prohibit group A from accessing the switch/queue/bindings for Group B, you must create a virtual host for A and b respectively. Each of the RABBITMQ servers has a default virtual host "/".

Switch: Exchange is used to forward messages, but it does not store, and if there is no Queue bind to Exchange, it discards the messages sent by Producer directly. Here is a more important concept: the routing key. When the message is to the switch, the interaction is forwarded to the corresponding queue, and then to which queue it is forwarded depends on the routing key.

Bindings: That is, the switch needs to be bound to the queue, which, as shown, is a many-to-many relationship.


The first is the configuration file.

#spring. application.name=spring-boot-rabbitmqspring.rabbitmq.host=127.0.0.1spring.rabbitmq.port= 5672spring.rabbitmq.username=guestspring.rabbitmq.password=guest


Sent by:

package com.basic.rabbitmq.send;import com.basic.rabbitmq.configuration.rabbitmqconfig2;import  org.springframework.amqp.core.amqptemplate;import org.springframework.beans.factory.annotation.autowired; Import org.springframework.stereotype.component;import org.springframework.stereotype.service;import  java.util.date;/** * created by sdc on 2017/6/17. */@Service (" Hellosender ") public class hellosender {     @Autowired      private AmqpTemplate amqpTemplate;//    private Rabbitt     public void send ()  {        String  contenxt =  "Order_queue_message";         This.amqpTemplate.convertAndSend (Rabbitmqconfig2.queue_exchange_name, "order_queue_routing", CONTENXT);//         this. amqptemplate.conver    }} 


Configuration information:

package com.basic.rabbitmq.configuration;import com.basic.rabbitmq.receiver.receiver;import  com.rabbitmq.client.channel;import com.rabbitmq.client.confirmlistener;import  org.springframework.amqp.core.*;import  org.springframework.amqp.rabbit.connection.cachingconnectionfactory;import  org.springframework.amqp.rabbit.connection.connectionfactory;import  org.springframework.amqp.rabbit.core.channelawaremessagelistener;import  org.springframework.amqp.rabbit.listener.messagelistenercontainer;import  org.springframework.amqp.rabbit.listener.simplemessagelistenercontainer;import  org.springframework.amqp.rabbit.listener.adapter.messagelisteneradapter;import  org.springframework.context.annotation.bean;import org.springframework.context.annotation.configuration; import java.io.ioexception;/** * created by sdc on 2017/6/17. */@ configurationpublic class rabbitmqconfig2 {    public static final string queue_name =  "Order_queue";     public static final String QUEUE_EXCHANGE_NAME =  "Topic_exchange_new ";    public static final  string routing_key = " Order_ Queue_routing ";     @Bean     public queue queue ()  {         //is persistent         boolean  durable = false;        //only the creator can use the queue, and automatically delete after disconnecting          boolean exclusive = false;         //If all consumers are disconnected, delete the queue         boolean  Autodelete = false;        return new queue (QUEUE_ Name, durable, excLusive, autodelete);    }     @Bean     public  topicexchange exchange ()  {        //is persistent          boolean durable = false;         //whether to delete the queue when all consumers are disconnected         boolean autodelete  = false;        return  new topicexchange ( Queue_exchange_name, durable, autodelete);    }     @Bean     public binding binding ()  {         return bindingbuilder.bind (Queue ()). to (Exchange ()). with (Routing_key);     }      @Bean     public connectionfactory connectionfactory ()  {        cachingconnectionfactory connectionfactory = new  Cachingconnectionfactory ("127.0.0.1", 5672);         Connectionfactory.setusername ("admin");         Connectionfactory.setpassword ("admin");         Connectionfactory.setvirtualhost ("/");        /**  if you want to make a message callback, This must be set to True */        connectionfactory.setpublisherconfirms ( true); //  must be set//         Connectionfactory.setpublisherreturns ();        return  connectionfactory;    }     @Bean      Simplemessagelistenercontainer container ()  {         Simplemessagelistenercontainer container = nEw simplemessagelistenercontainer ();         Container.setconnectionfactory (ConnectionFactory ());//         Container.setqueuenames (queue_name);         container.setqueues (QUEUE ( ));         container.setacknowledgemode (AcknowledgeMode.MANUAL);  Set Confirmation mode manually confirm         container.setmessagelistener (new  Channelawaremessagelistener ()  {            @ override            public void  OnMessage (Message message, channel channel)  throws Exception {                 byte[] body =  Message.getbody ();        &nbSP;        SYSTEM.OUT.PRINTLN ("Receive Message  : "  + new  string (body));                 channel.queuedeclare (queue_name, true, false, false, null);//                 channel.basicack ( Message.getmessageproperties (). Getdeliverytag (),  false);  //confirmation message successful consumption//                 channel.basicack ();  //answer//                 channel.basicreject ();//Reject                  Channel.basicrecover ();  //recovery//                 channel.basicqos ();//                 Channel.addconfirmlistener (New confirmlistener ()  {//                      @Override//                     public  Void handleack (long deliverytag, boolean multiple)  throws ioexception {//                          //failed to re-send//                     }////                      @Override//            &nbsP;        public void handlenack (Long deliveryTag,  boolean multiple)  throws IOException {//                         //Confirm ok//                      }//                 });            }         });        return  container;     }//     @Bean//    messagelisteneradapter  ListenerAdapter (Receiver receiver)  {//        return  New messagelisteneradapter (receiver,  "ReceiveMessage");//    }} 


Test class:

Package Com.rabbit.test;import Com.basic.rabbitmq.send.hellosender;import Com.basic.system.application;import Org.junit.test;import Org.junit.runner.runwith;import org.springframework.beans.factory.annotation.Autowired; Import Org.springframework.boot.test.context.springboottest;import Org.springframework.test.context.junit4.springrunner;import javax.annotation.resource;/** * Created by SDC on 2017/6/    */@RunWith (Springrunner.class) @SpringBootTest (classes = application.class) public class Rabbitmqtest {@Autowired    Public Hellosender Hellosender;    @Test public void Helloword () throws Exception {hellosender.send (); }}


This is just a demo, when learning to test a variety of things, on the basis of change on it, the mind of the doubts of the test can write some projects.

This article is from the "10093778" blog, please be sure to keep this source http://10103778.blog.51cto.com/10093778/1944218

RABBITMQ Integrated spring boot Message Queue Starter Demo

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.