Exploring the RABBITMQ of the analytic micro-service

Source: Internet
Author: User
Tags failover rabbitmq

Z Overview

This article mainly describes how to use the RABBITMQ message agent to realize the communication between distributed systems, thus facilitating the loose coupling of microservices.

RabbitMQ, also known as the open source message broker, supports a variety of message protocols and can be deployed on distributed systems. It is lightweight and easy to deploy applications. It primarily acts as a queue in which messages entered can be manipulated first. RABBITMQ can run in many operating systems and cloud environments, and provides a wide range of development tools for most popular languages. It is producer-consumer mode, producer sends out information, consumer consumption information. The main features of RABBITMQ are as follows:

Asynchronous messages

Distributed deployment

Management and Monitoring

Enterprise and cloud Computing

Installation

For RABBITMQ, you first need to install Erlang in the system, because RABBITMQ is written in Erlang. After installing Erlang, you can download the latest version of RabbitMQ from its website by following the introduction below.

Using RABBITMQ in MicroServices

In your microservices architecture, RABBITMQ is one of the simplest free options available for implementing Message Queuing. These queue patterns help to decouple the communication between the various microservices to increase the elasticity of the application. We can use these queues for various purposes, such as interaction between core microservices, decoupling of microservices, implementing failover mechanisms, and sending e-mail notifications via the message agent.

Wherever there are two or more two core modules that need to communicate with each other, we should not make direct HTTP calls, as they will result in tight coupling of the core layer and will be difficult to manage when each core module has more instances. and the HTTP invocation pattern fails every time the service goes down because we won't be able to track the old HTTP request call after the service restarts. This creates a demand for RABBITMQ.

Picture description (max. 50 words)

Setting up RABBITMQ in MicroServices

In the MicroServices architecture, for demonstration purposes, we will use an example pattern that can send e-mail notifications through any core microservices. In this mode, we will have a producer that can have any core microservices, which will generate the e-mail content and send it to the queue. The e-mail content is then handled by consumers who are always waiting for new messages in the queue.

Note that because you are building microservices with spring boot, we will provide the configuration for spring.

1) Producer: This layer is responsible for generating e-mail content and sending this content to the message agent in RABBITMQ.

A) in the properties file, we need to configure the queue name and interchange type, as well as the host and port where the RABBITMQ server is installed.

Queue.name=messagequeue

Fanout.exchange=messagequeue-exchange

Spring.rabbitmq.host:localhost

spring.rabbitmq.port:5672

Spring.rabbitmq.username:guest

Spring.rabbitmq.password:guest

b) We need to create a configuration class that binds the queue to the MicroServices module using the queue name and interchange type.

@Configuration

public class Rabbitconfiguration {

@Value ("${fanout.exchange}")

Private String Fanoutexchange;

@Value ("${queue.name}")

Private String queuename;

@Bean

Queue Queue () {

return new Queue (QueueName, true);

}

@Bean

Fanoutexchange Exchange () {

return new Fanoutexchange (Fanoutexchange);

}

@Bean

Binding binding (Queue queue, Fanoutexchange Exchange) {

return Bindingbuilder.bind (Queue). to (Exchange);

}

}

c) Finally, we need a tool class that will send the actual e-mail content to the queue using the rabbittemplate provided by the spring framework.

@Component

public class Queueproducer {

protected Logger Logger = Loggerfactory.getlogger (GetClass ());

@Value ("${fanout.exchange}")

Private String Fanoutexchange;

Private final rabbittemplate rabbittemplate;

@Autowired

Public Queueproducer (Rabbittemplate rabbittemplate) {

Super ();

This.rabbittemplate = rabbittemplate;

}

public void produce (Notificationrequestdto notificationdto) throws Exception {

Logger.info ("Storing notification ...");

Rabbittemplate.setexchange (Fanoutexchange);

Rabbittemplate.convertandsend (New Objectmapper (). writevalueasstring (Notificationdto));

Logger.info ("Notification stored in queue sucessfully");

}

}

D) You can then call this produce method anywhere in the module.

{

Queueproducer.produce (notificationdto);

}

2) Consumer: This layer is responsible for consuming messages from the RABBITMQ message agent using the FIFO method, and then performing e-mail-related operations.

A) In this properties file, we need to configure the queue name and interchange type, as well as the host and port where the RABBITMQ server is installed.

Queue.name=messagequeue

Fanout.exchange=messagequeue-exchange

Spring.rabbitmq.host:localhost

spring.rabbitmq.port:5672

Spring.rabbitmq.username:guest

Spring.rabbitmq.password:guest

b) We need to create a configuration class that binds the queue to the MicroServices module using the queue name and interchange type. In addition, in the consumer's RABBITMQ configuration, we need to create a messagelisteneradapter bean that acts as a consumer that always listens to incoming messages in the queue. This messagelisteneradapter will have a parametric constructor with a consumer tool class and a defaultlistenermethod, where we can specify the actions related to e-mail.

@Configuration

public class Rabbitconfiguration {

private static final String Listener_method = "ReceiveMessage";

@Value ("${queue.name}")

Private String queuename;

@Value ("${fanout.exchange}")

Private String Fanoutexchange;

@Bean

Queue Queue () {

return new Queue (QueueName, true);

}

@Bean

Fanoutexchange Exchange () {

return new Fanoutexchange (Fanoutexchange);

}

@Bean

Binding binding (Queue queue, Fanoutexchange Exchange) {

return Bindingbuilder.bind (Queue). to (Exchange);

}

@Bean

Simplemessagelistenercontainer container (ConnectionFactory connectionfactory,

Messagelisteneradapter ListenerAdapter) {

Simplemessagelistenercontainer container = new Simplemessagelistenercontainer ();

Container.setconnectionfactory (ConnectionFactory);

Container.setqueuenames (QueueName);

Container.setmessagelistener (ListenerAdapter);

return container;

}

@Bean

Messagelisteneradapter ListenerAdapter (Queueconsumer consumer) {

return new Messagelisteneradapter (consumer, Listener_method);

}

}

c) Then, you need to create a Queueconsumer class with a specific message listener method in which we can actually send an e-mail message.

@Component

public class Queueconsumer {

@Autowired

Mailserviceimpl Mailserviceimpl;

protected Logger Logger = Loggerfactory.getlogger (GetClass ());

public void ReceiveMessage (String message) {

Logger.info ("Received (String)" + message);

ProcessMessage (message);

}

public void ReceiveMessage (byte[] message) {

String strmessage = new string (message);

Logger.info ("Received (No String)" + strmessage);

ProcessMessage (strmessage);

}

private void ProcessMessage (String message) {

try {

Maildto maildto = new Objectmapper (). ReadValue (message, maildto.class);

Validationutil.validatemaildto (maildto);

Mailserviceimpl.sendmail (maildto, NULL);

} catch (Jsonparseexception e) {

Logger.warn ("Bad JSON in message:" + message);

} catch (Jsonmappingexception e) {

Logger.warn ("Cannot map JSON to notificationrequest:" + message);

} catch (Exception e) {

Logger.error (E.getmessage ());

}

}

}

Summarize

By using RABBITMQ, you can avoid direct HTTP calls between services and eliminate the tight coupling of core microservices. This will help you achieve the scalability of microservices at a higher level and add a failover mechanism between microservices.

Explore RABBITMQ under micro-service analysis

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.