Example code for using RABBITMQ in Spring boot

Source: Internet
Author: User
Tags rabbitmq

It's been a long time since I wrote spring boot, and I've been writing about spring Cloud Bus recently, because the content will have some relevance, so I'm going to fill out an integration of AMQP.

http://www.ljhseo.com/
http://www.xyrjkf.net/
http://www.xyrjkf.cn/
http://www.xyrjkf.com.cn/
http://www.zjdygsi.cn/
http://www.zjdaiyun.cn/
http://www.jsdygsi.cn/
http://www.xyrjkf.top/
http://www.xyrjkf.com/
http://www.daiyunzj.cn/
http://ljhseo.com/
http://xyrjkf.net/
http://xyrjkf.cn/
http://xyrjkf.com.cn/
http://zjdygsi.cn/
http://zjdaiyun.cn/
http://jsdygsi.cn/
http://xyrjkf.top/
http://xyrjkf.com/
http://daiyunzj.cn/

Introduction to Message Broker and AMQP

Message Broker is a schema pattern for messaging authentication, transmission, and routing that is primarily designed for the following scenarios:

    1. Messages routed to one or more destinations
    2. Messages into other ways of expression
    3. Performs the aggregation of messages, the decomposition of messages, and sends the results to their destination, and then re-group them back to the message user
    4. Invoking a Web service to retrieve data
    5. Responding to an event or error
    6. Use the Publish-subscribe pattern to provide content or topic-based message routing

AMQP is the abbreviation for Advanced Message Queuing protocol, which is an open standard Application layer protocol for message middleware. AMQP defines these features:

    1. Message direction
    2. Message Queuing
    3. Message routing (includes: Point-to-dot and publish-subscribe modes)
    4. Reliability
    5. Security

RabbitMQ

The RABBITMQ introduced in this paper is a middleware product implemented with the AMQP protocol, which can support many operating systems, multiple programming languages and almost all the mainstream enterprise-level technology platforms.

Installation

In the download page https://www.rabbitmq.com/download.html of the RABBITMQ website, we can obtain installation packages and documentation for a variety of different operating systems. Here, we will explain to a few common platform one by one.

The following is a description of the Erlang and RABBITMQ server versions that we use:

    1. ERLANG/OTP 19.1
    2. RabbitMQ Server 3.6.5

Windows installation

Install Erland, get EXE installation package via official download page http://www.erlang.org/downloads, open and complete the installation directly.

Install RABBITMQ, https://www.rabbitmq.com/download.html get EXE installation package via official download page.

When the download is complete, run the installer directly.

After the RabbitMQ server installation is complete, it is automatically registered as a service and starts up with the default configuration.

MAC OS x Installation

Using the Brew tool in Mac OS X, it is easy to install the RABBITMQ server, just follow the following command:

    1. Brew update to latest version, execute: Brew update
    2. Install Erlang, execute: Brew install Erlang
    3. Install RABBITMQ Server, execute: Brew install RABBITMQ

With the above command, the RabbitMQ Server command will be installed to/usr/local/sbin and will not be automatically added to the user's environment variables, so we need to add the following in the. bash_profile or. profile file:

    1. Path= $PATH:/usr/local/sbin
Copy Code

In this way, we can start the service of RABBITMQ by Rabbitmq-server command.

Ubuntu installation

In Ubuntu, we can use the APT repository to install

Install Erlang, execute: Apt-get install Erlang
Execute the following command to add the APT warehouse to/ETC/APT/SOURCES.LIST.D

    1. Echo ' deb http://www.rabbitmq.com/debian/testing main ' |
    2. sudo tee/etc/apt/sources.list.d/rabbitmq.list
Copy Code

Update the APT Warehouse's package list, execute the sudo apt-get update command

Install rabbit Server, execute the sudo apt-get install rabbitmq-server command

Rabbit Management

We can manage it directly through access to the profile, or through Web Access. Below we will show you how to manage through the web.

Execute the Rabbitmq-plugins enable rabbitmq_management command to open the Web management plugin so that we can manage it through the browser.

    1. > Rabbitmq-plugins Enable Rabbitmq_management
    2. The following plugins has been enabled:
    3. Mochiweb
    4. Webmachine
    5. Rabbitmq_web_dispatch
    6. Amqp_client
    7. Rabbitmq_management_agent
    8. Rabbitmq_management
    9. Applying plugin configuration to [email protected] started 6 plugins.
Copy Code

Open the browser and access: http://localhost:15672/, and use the default user guest login, the password is also guest. We can see the administration page as follows:

, we can see some of the basic concepts mentioned in the previous chapters, such as Connections, Channels, exchanges, queue, and so on. The first use of the reader, can be opened to see what the content, familiar with the RABBITMQ Server service side.

Click the Admin tab, where you can manage the user.

Spring Boot Integration

Below, we have an intuitive feeling and understanding of RABBITMQ by consolidating RABBITMQ in the Spring boot application and implementing a simple example of sending and receiving messages.

It's easy to integrate RABBITMQ in spring boot, because we've already introduced starter POMs, where the AMQP modules can be very well supported RABBITMQ, let's talk about the integration process in detail:

Create a new spring boot project named: "Rabbitmq-hello".

The following dependencies are introduced in Pom.xml, where SPRING-BOOT-STARTER-AMQP is used to support RABBITMQ.

    1. <parent>
    2. <groupId>org.springframework.boot</groupId>
    3. <artifactId>spring-boot-starter-parent</artifactId>
    4. <version>1.3.7.RELEASE</version>
    5. <relativePath/> <!--lookup parent from repository to
    6. </parent>
    7. <dependencies>
    8. <dependency>
    9. <groupId>org.springframework.boot</groupId>
    10. <artifactId>spring-boot-starter-amqp</artifactId>
    11. </dependency>
    12. <dependency>
    13. <groupId>org.springframework.boot</groupId>
    14. <artifactId>spring-boot-starter-test</artifactId>
    15. <scope>test</scope>
    16. </dependency>
    17. </dependencies>
Copy Code

Configuring connection and user information about RABBITMQ in Application.properties, users can go back to the installation content above and create users in the Administration page.
Spring.application.name=rabbitmq-hello

    1. Spring.rabbitmq.host=localhost
    2. spring.rabbitmq.port=5672
    3. Spring.rabbitmq.username=spring
    4. spring.rabbitmq.password=123456
Copy Code

Create message producer sender. By injecting an instance of the Amqptemplate interface to deliver the message, the Amqptemplate interface defines a set of underlying operations for the AMQP protocol. The specific implementation is injected in spring boot based on the configuration. In the producer, we generate a string and send it to the queue named Hello.

    1. @Component
    2. public class Sender {
    3. @Autowired
    4. Private Amqptemplate rabbittemplate;
    5. public void Send () {
    6. String context = "Hello" + new Date ();
    7. System.out.println ("Sender:" + context);
    8. This.rabbitTemplate.convertAndSend ("Hello", context);
    9. }
    10. }
Copy Code

Create a message consumer receiver. This class listens to the Hello queue by @rabbitlistener annotations and uses @rabbithandler annotations to specify how the message is handled. Therefore, the consumer realizes the consumption of the Hello queue, the consumption operation is the string content of the output message.

    1. @Component
    2. @RabbitListener (queues = "Hello")
    3. public class Receiver {
    4. @RabbitHandler
    5. public void process (String hello) {
    6. System.out.println ("Receiver:" + hello);
    7. }
    8. }
Copy Code

Create RABBITMQ Configuration Class Rabbitconfig, which is used to configure advanced information such as queues, switches, routes, and so on. Here we start with a minimum of configuration to define, to complete a basic production and consumption process.

    1. @Configuration
    2. public class Rabbitconfig {
    3. @Bean
    4. Public Queue Helloqueue () {
    5. return new Queue ("Hello");
    6. }
    7. }
Copy Code

To create an app main class:

    1. @SpringBootApplication
    2. public class Helloapplication {
    3. public static void Main (string[] args) {
    4. Springapplication.run (Helloapplication.class, args);
    5. }
    6. }
Copy Code

Create a unit test class to invoke the message production:

    1. @RunWith (Springjunit4classrunner.class)
    2. @SpringApplicationConfiguration (classes = helloapplication.class)
    3. public class Helloapplicationtests {
    4. @Autowired
    5. Private sender Sender;
    6. @Test
    7. public void Hello () throws Exception {
    8. Sender.send ();
    9. }
    10. }
Copy Code

After the program has been written, try running below. First make sure that RABBITMQ server has started, and then do the following:

Launch the application main class, from the console, we see the following, the program creates a connection to access the Springcloud in 127.0.0.1:5672.

The code is as follows. s.a.r.c.cachingconnectionfactory:created New connection: [email protected] [Delegate=amqp://[email protected] : 5672/]

At the same time, through the RABBITMQ Control Panel, we can see the entries in connection and channels that contain the current connection.

Running the Unit test class, we can see the output below in the console, and the message is sent to the RABBITMQ server's Hello queue.

    1. Sender:hello Sun Sep 11:06:11 CST 2016
Copy Code

Switching to the console of the application main class, we can see output similar to the following, the consumer to the Hello Queue listener execution, and output the received message information.

    1. Receiver:hello Sun Sep 11:06:11 CST 2016
Copy Code

Using the example above, we introduced the SPRING-BOOT-STARTER-AMQP module to the Spring boot application, and the development of RABBITMQ's message production and consumption was completed with a simple configuration. However, in the practical application, we still have a lot of content without demonstration, here do not do more explanation, the reader can consult RABBITMQ's official tutorial, have a more comprehensive understanding.

Example code for using RABBITMQ in Spring boot

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.