Simple Spring Boot & RabbitMq configuration
Let’s start with YAML configuration
spring:
rabbitmq:
host: localhost
port: 5672
username: guest
password: guestmyapp:
rabbitmq:
exchange-name: my-app-exhange-name
Create a new class named RabbitMqConfiguration
@Configuration
public class RabbitMqConfiguration {@Value("${myapp.rabbitmq.exchange-name}")
private String exchangeName;@Bean
Queue someQueue() {
return new Queue("someQueue", false);
}@Bean
Queue anotherQueue() {
return new Queue("anotherQueue", false);
}@Bean
public DirectExchange directExchange() {
return new DirectExchange(exchangeName);
}@Bean
Binding someBinding(final Queue someQueue, DirectExchange exchange) {
return BindingBuilder.bind(someQueue).to(exchange).with("some-router");
}@Bean
Binding anotherBinding(final Queue anotherQueue, DirectExchange exchange) {
return BindingBuilder.bind(anotherQueue).to(exchange).with("another-router");
}}
Let’s listen these queues. Create a new class named SomeQueueListener
@Service
public class SomeQueueListener {
@RabbitListener(queues = "someQueue")
public void handleSomeJob(String workId) {
System.out.printf("Working on SomeQueue... %s%n", workId);
}
}
Then AnotherQueueListener
@Service
public class AnotherQueueListener {
@RabbitListener(queues = "anotherQueue")
public void handleAnotherJob(String workId) {
System.out.printf("Working on anotherQueue... %s%n", workId);
}
}
Now we need a producer to send job to rabbit’s queue. Create a new class named SomeJobProducer
@RequiredArgsConstructor // I like lombok
@Service
public class SomeJobProducer {
private final RabbitTemplate rabbitTemplate; @Value("${myapp.rabbitmq.exchange-name}")
private String exchangeName;
public void sendToQueue(String workId) {
rabbitTemplate.convertAndSend(exchangeName, "some-router", workId);
}
}
Then AnotherJobProducer
@RequiredArgsConstructor
@Service
public class AnotherJobProducer {
private final RabbitTemplate rabbitTemplate; @Value("${myapp.rabbitmq.exchange-name}")
private String exchangeName;
public void sendToQueue(String workId) {
rabbitTemplate.convertAndSend(exchangeName, "another-router", workId);
}
}
Here we go
@RequiredArgsConstructor
@Service
public class MyService{private final SomeJobProducer someJobProducer;
private final AnotherJobProducer anotherJobProducer;void doSomeWork(String workId){
someJobProducer.sendToQueue(workId);}void doAnotherWork(String workId){
anotherJobProducer.sendToQueue(workId);}
}
I tried to keep it as simple as I can, I’m sure there are many people who can explain the details better than me.