Spring Rest Service to Read Data From Rabbitmq
Introduction
Prerequisites
This tutorial assumes RabbitMQ is installed and running on localhost on the standard port (5672). In case you lot use a unlike host, port or credentials, connections settings would require adjusting.
Where to go assist
If you're having trouble going through this tutorial you can contact us through the mailing listing or RabbitMQ customs Slack.
RabbitMQ is a message broker: information technology accepts and forwards letters. Yous tin can think about information technology as a post role: when you put the mail that you want posting in a mail service box, you can be sure that the letter carrier will eventually deliver the mail to your recipient. In this analogy, RabbitMQ is a post box, a post office, and a letter carrier.
The major departure between RabbitMQ and the mail service office is that it doesn't deal with paper, instead information technology accepts, stores, and forwards binary blobs of information ‒ messages.
RabbitMQ, and messaging in general, uses some jargon.
-
Producing means nothing more than than sending. A program that sends letters is a producer :
digraph { bgcolor=transparent; truecolor=truthful; rankdir=LR; node [mode="filled"]; // P1 [label="P", fillcolor="#00ffff"]; }
-
A queue is the name for a mail box which lives inside RabbitMQ. Although messages flow through RabbitMQ and your applications, they can but be stored inside a queue. A queue is only bound by the host's retentiveness & disk limits, information technology'southward substantially a large message buffer. Many producers tin can send messages that go to one queue, and many consumers tin try to receive data from one queue. This is how nosotros represent a queue:
digraph { bgcolor=transparent; truecolor=true; rankdir=LR; node [style="filled"]; // subgraph cluster_Q1 { characterization="queue_name"; color=transparent; Q1 [label="{||||}", fillcolor="cerise", shape="record"]; }; }
-
Consuming has a similar meaning to receiving. A consumer is a program that more often than not waits to receive messages:
digraph { bgcolor=transparent; truecolor=true; rankdir=LR; node [style="filled"]; // C1 [label="C", fillcolor="#33ccff"]; }
Note that the producer, consumer, and broker exercise not have to reside on the aforementioned host; indeed in about applications they don't. An application tin be both a producer and consumer, too.
"Hello Earth"
(using Jump AMQP)
In this part of the tutorial nosotros'll write 2 programs using the spring-amqp library; a producer that sends a single message, and a consumer that receives messages and prints them out. We'll gloss over some of the detail in the Leap AMQP API, concentrating on this very elementary thing just to get started. It's a "Hello World" of messaging.
In the diagram below, "P" is our producer and "C" is our consumer. The box in the middle is a queue - a message buffer that RabbitMQ keeps on behalf of the consumer.
The Spring AMQP Framework
RabbitMQ speaks multiple protocols. This tutorial uses AMQP 0-9-i, which is an open, full general-purpose protocol for messaging. There are a number of clients for RabbitMQ in many different languages.
Nosotros'll exist using Bound Boot to bootstrap and configure our Spring AMQP project. We chose Maven to build the project, but we could have used Gradle as well.
The source lawmaking of the projection is available online, but you can also do the tutorials from scratch.
If you lot choose the afterward, open the Leap Initializr and provide: the group id (e.g. org.springframework.amqp.tutorials) the antiquity id (east.g. rabbitmq-amqp-tutorials) Search for the RabbitMQ dependency and select the RabbitMQ dependency.
Generate the project and unzip the generated project into the location of your choice. This can now be imported into your favorite IDE. Alternatively you tin work on it from your favorite editor.
Configuring the project
Bound Boot offers numerous features merely we will only highlight a few here. Starting time, Spring Kicking applications have the pick of providing their properties through either an awarding.properties or application.yml file (there are many more options as well but this volition get us going). You'll find an application.properties file in the generated project with nothing in it. Rename application.properties to application.yml file with the following backdrop:
spring: profiles: active: usage_message logging: level: org: ERROR tutorial: client: duration: 10000
Create a new package tut1 where nosotros can put the tutorial code. We'll now create a Coffee configuration file Tut1Config.coffee to describe our Bound beans in the following manner:
package org.springframework.amqp.tutorials.tut1; import org.springframework.amqp.core.Queue; import org.springframework.context.annotation.Edible bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Contour; @Profile({"tut1","hello-world"}) @Configuration public class Tut1Config { @Bean public Queue hello() { render new Queue("hello"); } @Profile("receiver") @Bean public Tut1Receiver receiver() { return new Tut1Receiver(); } @Contour("sender") @Bean public Tut1Sender sender() { return new Tut1Sender(); } } Note that we've divers the showtime tutorial profile as either tut1, the package proper name, or hullo-world. We employ the @Configuration annotation to let Spring know that this is a Coffee Configuration and in it nosotros create the definition for our Queue ("hello") and ascertain our Sender and Receiver beans.
We will run all of our tutorials through the Boot Application now by simply passing in which profiles we are using. To enable this we volition alter the generated RabbitAmqpTutorialsApplication class with the following:
import org.springframework.boot.CommandLineRunner; import org.springframework.kicking.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Profile; import org.springframework.scheduling.annotation.EnableScheduling; @SpringBootApplication @EnableScheduling public form RabbitAmqpTutorialsApplication { @Profile("usage_message") @Bean public CommandLineRunner usage() { return args -> { Arrangement.out.println("This app uses Spring Profiles to control its behavior.\northward"); System.out.println("Sample usage: coffee -jar rabbit-tutorials.jar --spring.profiles.active=hello-world,sender"); }; } @Profile("!usage_message") @Bean public CommandLineRunner tutorial() { return new RabbitAmqpTutorialsRunner(); } public static void master(String[] args) throws Exception { SpringApplication.run(RabbitAmqpTutorialsApplication.grade, args); } } and add together the RabbitAmqpTutorialsRunner class as follows:
package org.springframework.amqp.tutorials.tut1; import org.springframework.beans.factory.notation.Autowired; import org.springframework.beans.factory.note.Value; import org.springframework.boot.CommandLineRunner; import org.springframework.context.ConfigurableApplicationContext; public form RabbitAmqpTutorialsRunner implements CommandLineRunner { @Value("${tutorial.client.duration:0}") private int duration; @Autowired private ConfigurableApplicationContext ctx; @Override public void run(Cord... arg0) throws Exception { Organization.out.println("Ready ... running for " + duration + "ms"); Thread.sleep(duration); ctx.shut(); } } Sending
At present there is very little code that needs to become into the sender and receiver classes. Allow'due south telephone call them Tut1Receiver and Tut1Sender. The sender leverages our configuration and the RabbitTemplate to send the bulletin.
// Sender package org.springframework.amqp.tutorials.tut1; import org.springframework.amqp.core.Queue; import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.note.Scheduled; public class Tut1Sender { @Autowired individual RabbitTemplate template; @Autowired private Queue queue; @Scheduled(fixedDelay = k, initialDelay = 500) public void send() { String message = "Hi Earth!"; this.template.convertAndSend(queue.getName(), message); System.out.println(" [x] Sent '" + message + "'"); } } Yous'll notice that Spring AMQP removes the boilerplate code leaving you with only the logic of the messaging to exist concerned about. We autowire in the queue that was configured in our bean definition in the Tut1Config class and similar many spring connexion abstractions, we wrap the boilerplate RabbitMQ customer classes with a RabbitTemplate that tin can exist autowired into the sender. All that is left is to create a message and invoke the template's convertAndSend method passing in the queue name from the edible bean nosotros divers and the message nosotros just created.
Sending doesn't work!
If this is your beginning time using RabbitMQ and you don't see the "Sent" message then you may be left scratching your head wondering what could exist wrong. Peradventure the banker was started without enough costless deejay space (by default information technology needs at to the lowest degree 200 MB free) and is therefore refusing to accept messages. Cheque the broker logfile to confirm and reduce the limit if necessary. The configuration file documentation will prove you lot how to set disk_free_limit.
Receiving
The receiver is every bit simple. We annotate our receiver class with @RabbitListener and laissez passer in the name of the queue. We and so annotate our receive method with @RabbitHandler passing in the payload that has been pushed to the queue.
package org.springframework.amqp.tutorials.tut1; import org.springframework.amqp.rabbit.annotation.RabbitHandler; import org.springframework.amqp.rabbit.notation.RabbitListener; @RabbitListener(queues = "hello") public class Tut1Receiver { @RabbitHandler public void receive(String in) { System.out.println(" [10] Received '" + in + "'"); } } Putting it all together
We must now build the JAR file:
./mvnw clean packet
The application uses Spring Profiles to command what tutorial information technology'southward running, and whether information technology'due south a sender or receiver. To run the receiver, execute the following command:
# consumer java -jar target/rabbitmq-tutorials.jar --spring.profiles.active=how-do-you-do-world,receiver
Open up another vanquish to run the sender:
# sender java -jar target/rabbitmq-tutorials.jar --spring.profiles.agile=hello-globe,sender
List queues
You may wish to meet what queues RabbitMQ has and how many messages are in them. You can exercise information technology (equally a privileged user) using the rabbitmqctl tool:
sudo rabbitmqctl list_queuesOn Windows, omit the sudo:
rabbitmqctl.bat list_queues
Time to movement on to role two and build a simple work queue.
Production [Not-]Suitability Disclaimer
Please keep in listen that this and other tutorials are, well, tutorials. They demonstrate 1 new concept at a time and may intentionally oversimplify some things and go out out others. For case topics such as connexion management, error handling, connection recovery, concurrency and metric collection are largely omitted for the sake of brevity. Such simplified code should not be considered production set up.
Please have a look at the remainder of the documentation before going alive with your app. We particularly recommend the following guides: Publisher Confirms and Consumer Acknowledgements, Product Checklist and Monitoring.
Getting Help and Providing Feedback
If you lot have questions virtually the contents of this tutorial or whatsoever other topic related to RabbitMQ, don't hesitate to ask them on the RabbitMQ mailing list.
Help Us Ameliorate the Docs <3
If you'd like to contribute an comeback to the site, its source is bachelor on GitHub. Simply fork the repository and submit a pull request. Thank you!
Source: https://www.rabbitmq.com/tutorials/tutorial-one-spring-amqp.html
Post a Comment for "Spring Rest Service to Read Data From Rabbitmq"