The previous article talked about using RabbitMQ to send messages, and this article will talk about receiving messages.
In traditional JMS, there are two ways to obtain information from the queue, the synchronous method using JmsTemplate and the asynchronous method using message-driven pojo. Spring AMQP also provides a similar way to obtain messages sent via AMQP.
The simplest method of receiving information provided by RabbitTemplate is the receive() method, through which you can obtain a Message object from the queue:
Message message = rabbit.receive("spittle.test.queue");
Or you can also obtain the default queue of messages through configuration. This is achieved by setting the queue attribute when configuring the template:
This way If so, when calling the receive() method, the message can be obtained from the default queue without setting any parameters:
Message message = rabbit.receive( );
After obtaining the Message object, you generally need to set its body attribute Convert the byte array in to the desired object. Just like converting the domain object to the Message when sending, converting the received Message to the domain object is also tedious. Here you can consider using RabbitTemplate's receiveAndConvert() method as an alternative:
Spittle spittle = (Spittle) rabbit.receiveAndConvert("spittle.test.queue");
The receiveAndConvert() method will use the same message converter as the sendAndConvert() method to convert the Message object into the original type.
Calling the receive() and receiveAndConvert() methods will return immediately. If there are no waiting messages in the queue, you will get null. At this time, programmers generally need to manage polling and necessary threads themselves to implement queue monitoring. If you don't want to poll synchronously every time to wait for the message to arrive, you can use the message-driven pojo provided by Spring AMQP. Let's take a look at using the message-driven pojo to receive messages.
If you want to consume Spittle objects asynchronously in message-driven pojo, you must first solve the pojo itself, as shown below SpittleTestHandler Playing this role:
public class SpittleTestHandler {public void handleSpittleTest (Spittle spittle) { ... } }
In fact, this class does not depend on AMQP. No matter what mechanism is passed to the Spittle object, it can handle it.
Here you also need to declare SpittleTestHandler as a bean in the Spring application context:
Finally, declare a listener container and listener, which can be called when the message arrives SpittleTestHandler, the configuration is as follows:
The
The above is the detailed content of Using Spring and AMQP to send and receive messages in java (Part 2). For more information, please follow other related articles on the PHP Chinese website!