1 Preface
Spring Cloud Stream
is designed for event-driven microservices systems that use messaging middleware to send and receive messages. Using Spring Cloud Stream
allows you to focus on business development without spending too much effort on the interaction between the application and the MQ. Also, you don’t have to make many code changes after switching to MQ.
In this article, we will integrate Spring Cloud Stream
and RabbitMQ
to send and receive messages.
2 Integration process
2.1 Adding dependencies
Different MQs use different dependencies and are very easy to switch between.
2.2 Define the way to handle sending and receiving
Queues are nothing but receiving and sending, so we have to define first, how to send and how to receive.
To send a message.
Only one String
is sent, usually the business is usually Entity class. The content sent here is also fixed, and the actual business can get the data source by checking the database, reading the file, etc.
Receive message.
Just print the message directly, the logic in the project can be implemented by specific business.
2.3 Configuration properties
To configure RabbitMQ.
Related items for configuring Spring Cloud Stream
.
spring.cloud.stream.function.definition
will define the processing methods, such as the methods for sending and receiving messages in this article.
bindings
configures the corresponding function
; destination points to the subject of the MQ.
A poller
is paired here, and messages are sent every 500ms.
2.4 Running
First, start a RabbitMQ: poller
.
After running the program, it creates its own topics, sends messages, and receives messages.
The run log is as follows.
You can see that each send/receive is about 500ms apart, but of course it can’t be exactly 500ms.
3 Summary
The code can be found at: https://github.com/LarryDpk/pkslow-samples
Reference https://www.pkslow.com/archives/spring-cloud-stream-binder-rabbit