Springboot Combat (eight) of the RABBITMQ

Source: Internet
Author: User
Tags rabbitmq

What is RABBITMQ?

RabbitMQ is a message agent. Its core principle is very simple: to receive and send messages. You can think of it as a post office: If you put the letter in your mailbox, the postman will post the letter to your recipient. In this analogy, RabbitMQ plays the role of a mailbox, a post office, and a postman.

The main difference between RabbitMQ and the post office is that it is not used to process paper, it is used to receive, store, and send messages (message) of this binary data.

The main demonstration of this paper is SPRINGBOOT+RABBITMQ simple integration + Example description

With regard to installing RABBITMQ, since RABBITMQ is written in Erlang, the environment for Erlang must first be installed.

RABBITMQ installation Under Window can refer to this post link: 79288578

This blog post is very clear and detailed, I will not say more.

The following goes into the example:

One, MAVEN relies on

<?XML version= "1.0" encoding= "UTF-8"?><Projectxmlns= "http://maven.apache.org/POM/4.0.0"Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"xsi:schemalocation= "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">    <modelversion>4.0.0</modelversion>    <groupId>Org.springframework</groupId>    <Artifactid>Gs-messaging-rabbitmq</Artifactid>    <version>0.1.0</version>    <Parent>        <groupId>Org.springframework.boot</groupId>        <Artifactid>Spring-boot-starter-parent</Artifactid>        <version>1.5.8.RELEASE</version>    </Parent>    <Properties>        <Java. Version>1.8</java.version>    </Properties>    <Dependencies>        <Dependency>            <groupId>Org.springframework.boot</groupId>            <Artifactid>Spring-boot-starter-amqp</Artifactid>        </Dependency>    </Dependencies>    <Build>        <Plugins>            <plugin>                <groupId>Org.springframework.boot</groupId>                <Artifactid>Spring-boot-maven-plugin</Artifactid>            </plugin>        </Plugins>    </Build></Project>

II. Preparation of Receive

 PackageHello;ImportJava.util.concurrent.CountDownLatch;Importorg.springframework.stereotype.Component; @Component Public classReceiver {PrivateCountdownlatch latch =NewCountdownlatch (1);  Public voidreceiveMessage (String message) {System.out.println ("Received <" + message + ">");    Latch.countdown (); }     PublicCountdownlatch Getlatch () {returnlatch; }}

Receiveris a simple pojo that defines a method for receiving messages. When you register it to receive a message, you can name it whatever you want.

for the sake of convenience, this pojo also has a CountDownLatch . This allows it to signal that a message is received. This is not likely to be implemented in your production application.

registering listeners and sending messages

Spring AMQP RabbitTemplate provides everything you need to send and receive messages using RABBITMQ . Specifically, you need to configure:

    • Message Listener Container

    • Declaring queues, interchanges, and bindings between them

    • The component used to send some messages to test listeners

Iii. Preparation of Runner

 PackageHello;ImportJava.util.concurrent.TimeUnit;Importorg.springframework.amqp.rabbit.core.RabbitTemplate;ImportOrg.springframework.boot.CommandLineRunner;Importorg.springframework.stereotype.Component; @Component Public classRunnerImplementsCommandlinerunner {Private Finalrabbittemplate rabbittemplate; Private Finalreceiver receiver;  PublicRunner (receiver receiver, rabbittemplate rabbittemplate) { This. Receiver =receiver;  This. rabbittemplate =rabbittemplate; } @Override Public voidRun (String ... args)throwsException {System.out.println ("Sending message ..."); Rabbittemplate.convertandsend (Application.topicexchangename,"Foo.bar.baz", "Hello from rabbitmq!"); Receiver.getlatch (). await (10000, Timeunit.milliseconds); }}

Iv. Writing configuration Files

spring.application.name=spirng-boot-rabbitmq spring.rabbitmq.host=Localhostspring.rabbitmq.port =5672spring.rabbitmq.username=Guestspring.rabbitmq.password=guest

V. Writing the Startup class

 PackageHello;Importorg.springframework.amqp.core.Binding;ImportOrg.springframework.amqp.core.BindingBuilder;ImportOrg.springframework.amqp.core.Queue;ImportOrg.springframework.amqp.core.TopicExchange;Importorg.springframework.amqp.rabbit.connection.ConnectionFactory;ImportOrg.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;ImportOrg.springframework.amqp.rabbit.listener.adapter.MessageListenerAdapter;Importorg.springframework.boot.SpringApplication;Importorg.springframework.boot.autoconfigure.SpringBootApplication;ImportOrg.springframework.context.annotation.Bean; @SpringBootApplication Public classApplication {Static FinalString topicexchangename = "Spring-boot-exchange"; Static FinalString queuename = "Spring-boot"; @Bean Queue Queue () {return NewQueue (QueueName,false); } @Bean Topicexchange Exchange () {return NewTopicexchange (topicexchangename); } @Bean Binding binding (Queue queue, Topicexchange Exchange) {returnBindingbuilder.bind (queue). to (Exchange). With ("foo.bar.#"); } @Bean Simplemessagelistenercontainer container (connectionfactory connectionfactory, Messagelisteneradap ter listeneradapter) {Simplemessagelistenercontainer container=NewSimplemessagelistenercontainer ();        Container.setconnectionfactory (ConnectionFactory);        Container.setqueuenames (QueueName);        Container.setmessagelistener (ListenerAdapter); returncontainer; } @Bean messagelisteneradapter ListenerAdapter (receiver receiver) {return NewMessagelisteneradapter (receiver, "ReceiveMessage"); }     Public Static voidMain (string[] args)throwsinterruptedexception {springapplication.run (application.class, args). Close (); }}

Spring boot automatically creates connection factories and rabbittemplate, reducing the amount of code you have to write.

listenerAdapter()method in the defined bean is Register as a message listener container() in the defined container . It listens for messages in the "Spring-boot" queue. because Receiver The class is Pojo, you need to wrap it in the MessageListenerAdapter specified location to be called receiveMessage .

the main() method to start the process by creating a spring application context. This launches the Message listener container, which will start listening for messages. Runner A bean is then automatically executed : It RabbitTemplate retrieves from the context of the application and send "Hello from rabbitmq! the message in the "Spring-boot" queue. Finally, it closes the spring application context and the application ends.

Supplemental Note:the JMS queue and the AMQP queue have different semantics. For example, JMS sends queued messages to only one consumer. Although the AMQP queue performs the same operation, the AMQP generator does not send messages directly to the queue. Instead, the message is sent to the switch, and the switch can go to a single queue, or fan out to multiple queues, mimicking the concept of a JMS topic.

Springboot Combat (eight) of the 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.