In an ideal case, all microservice interactions are expected to happen asynchronously using publish-subscribe semantics. Spring Boot provides a hassle-free mechanism to configure messaging solutions:
In this example, we will create a Spring Boot application with a sender and receiver, both connected though an external queue. Perform the following steps:
Rabbit MQ 3.5.6 is used in this book.
$./rabbitmq-server
application.properties
file to reflect the RabbitMQ configuration. The following configuration uses the default port, username, and password of RabbitMQ:spring.rabbitmq.host=localhost spring.rabbitmq.port=5672 spring.rabbitmq.username=guest spring.rabbitmq.password=guest
TestQ
of the org.springframework.amqp.core.Queue
type to the Application.java
file under src/main/java
. RabbitMessagingTemplate
is a convenient way to send messages, which will abstract all the messaging semantics. Spring Boot provides all boilerplate configurations to send messages:@Component class Sender { @Autowired RabbitMessagingTemplate template; @Bean Queue queue() { return new Queue("TestQ", false); } public void send(String message){ template.convertAndSend("TestQ", message); } }
@RabbitListener
annotation. Spring Boot autoconfigures all the required boilerplate configurations:@Component class Receiver { @RabbitListener(queues = "TestQ") public void processMessage(String content) { System.out.println(content); } }
run
method of CommandLineRunner
to initiate the message sending. When the application is initialized, it invokes the run
method of CommandLineRunner
, as follows:@SpringBootApplication public class Application implements CommandLineRunner{ @Autowired Sender sender; public static void main(String[] args) { SpringApplication.run(Application.class, args); } @Override public void run(String... args) throws Exception { sender.send("Hello Messaging..!!!"); } }
Hello Messaging..!!!