In the previous part, we have tried Spring Cloud Stream pre-built component such as Sink, Source and Processor for building message driven microservices.
In this part, we will look at how to create custom binding classes with custom channels for publishing and retrieving messages with RabbitMQ.
Setting up the publisher application
The publisher application is almost similar as the previous article except the bindings and related configurations.
The previous article uses Source class (Spring Cloud Stream built-in component) for configuring the output message channel (@Output) for publishing messages. Here we are not going to use the built-in component and we will be developing a custom output binding class to build and configure the output message channel.
|
import org.springframework.cloud.stream.annotation.Output; |
|
import org.springframework.messaging.MessageChannel; |
|
|
|
public interface OrderSource |
|
{ |
|
String OUTPUT = "orderPublishChannel"; |
|
|
|
@Output(OUTPUT) |
|
MessageChannel create(); |
|
} |
we have declared a custom Source class with “orderPublishChannel” as the output message channel.
Now we need to bind this OrderSource class in the OrderController.
|
@Slf4j |
|
@EnableBinding(OrderSource.class) |
|
@RestController |
|
public class OrderController |
|
{ |
|
@Autowired |
|
private OrderSource source; |
|
|
|
@PostMapping("/orders/publish") |
|
public String publishOrder(@RequestBody Order order) |
|
{ |
|
source.create().send(MessageBuilder.withPayload(order).build()); |
|
log.info(order.toString()); |
|
return "order_published"; |
|
} |
|
} |
source.create() will configure the output message channel whose name is “orderPublishChannel“. The published messages will be delegated to the RabbitMQ exchange through the “orderPublishChannel“.
We need to change the application.properties based on the channel name as follows.
spring.cloud.stream.bindings.orderPublishChannel.destination=orders-exchange
Now we have completed the development of the publisher application with custom source bindings for publishing messages. Lets move forward with developing the consumer application.
Setting up the consumer application.
The consumer application is almost similar as the previous article except the bindings and related configurations.
The previous article uses Sink class (Spring Cloud Stream built-in component) for configuring the input message channel (@Input) for retrieving messages. Here we are not going to use the built-in component and we will be developing a custom input binding class to build and configure the input message channel.
Continue reading “Message Driven Microservices with Spring Cloud Stream and RabbitMQ (Publish and Subscribe messages) with custom bindings – Part 2” →