Consumer routing with Spring Cloud Stream

Spring Cloud Stream supports consumer routing, allowing us to decide which consumer will consume messages sent by a particular producer. We can route messages using message headers, payload content, or header content with expressions. Let’s explore this in detail in this tutorial!

First, we’ll create a new Spring Boot project with the Cloud Stream dependency as follows:

Similar to the previous tutorial, we also add the Spring Cloud Starter Stream Rabbit dependency:

and define the RabbitMQ information in the application.yml file as follow:

To use consumer routing with Spring Cloud Stream, enable it by defining the following properties:

By enabling this routing, Spring will automatically create a Function interface bean named functionRouter and a logical binding name functionRouter-in-0. You can use this logical binding name to bind to the exchange with the queue in RabbitMQ, and when a message is received by this functionRouter bean, it will route the message to the consumer we want.

I will define the binding for sending and receiving messages as follows:

As you can see, I’m using the StreamBridge class to send messages with the binding name sendMessage, and I’ve also defined two consumers that can consume messages using the Consumer interface as follows:

Routing using message header

To route using message headers, use the MessageBuilder class to build the message as follows:

The payload is the message we want to send. In the header, you must pass the header name spring.cloud.function.definition with the header value being the name of the consumer bean that you want to receive the message. In this example, I’m configuring it as receiveConsumer1, as you can see!

I also defined the bean of the CommandLineRunner interface to send messages using the StreamBridge class as follows:

Now, if you run the application, you will see the following result:

If you change the header value of the header name spring.cloud.function.definition to receiveConsumer2, you will see the message received from receiveConsumer2 as follows:

Routing using expression

To route with expressions, you can use the spring.cloud.function.routing-expression property, for example:

so, if you send a message containing the number 2:

then you will see the following result:

Change the message payload to “Hello 1” and you’ll see that consumer 1 receives the message!

You can also define expressions with the message header, for example:

khi đó, các bạn chỉ cần truyền message header eventType với giá trị là tên của consumer sẽ nhận message là được:

So, in this tutorial, I’ve shown you how to route messages to specific consumers. Use them appropriately depending on your needs!

Watch the video here:

 

Add Comment