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

1
2
3
4
<dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-stream-binder-rabbit</artifactId>
</dependency>

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.

1
2
3
4
5
6
7
8
@Bean
public Supplier<String> pkslowSource() {
  return () -> {
    String message = "www.pkslow.com";
    log.info("Sending value: " + message);
    return 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.

1
2
3
4
5
6
@Bean
public Consumer<String> pkslowSink() {
  return message -> {
    log.info("Received message " + message);
  };
}

Just print the message directly, the logic in the project can be implemented by specific business.

2.3 Configuration properties

To configure RabbitMQ.

1
2
3
4
5
6
spring:
  rabbitmq:
    host: localhost
    port: 5672
    username: pkslow
    password: 123456

Related items for configuring Spring Cloud Stream.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
spring:
  cloud:
    stream:
      function:
        definition: pkslowSource;pkslowSink
      bindings:
        pkslowSource-out-0:
         destination: pkslow-topic
        pkslowSink-in-0:
          destination: pkslow-topic
      poller:
        fixed-delay: 500

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.

1
2
3
4
5
docker run \
-e RABBITMQ_DEFAULT_USER=pkslow \
-e RABBITMQ_DEFAULT_PASS=123456 \
-p 5672:5672 -p 15672:15672 \
rabbitmq:3.8-management

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