Let’s Spring Boot the RabbitMQ. We’ll create a producer and consumer communicating via default exchange and messages being routed to a single queue according to the routing key.
Configuring Maven: pom.xml
- Create a Spring Boot project.
- Use
spring-boot-starter-amqp
dependency. Add
javax.el
as a support dependency for Spring AMQP.4.0.0 sk.upjs.ics.novotnyr spring-boot-amqp-demo 0.0.1-SNAPSHOT <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.2.4.RELEASE</version> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-amqp</artifactId> </dependency> <dependency> <groupId>org.glassfish</groupId> <artifactId>javax.el</artifactId> <version>3.0.0</version> <scope>runtime</scope> </dependency> </dependencies>
Producer
AMQP starter for Spring Boot enables the following features:
- preconfigured
RabbitTemplate
- preconfigured
CachingConnectionFactory
- preconfigured
AmqpAdmin
In the following code, a message is sent to the default exchange with demo
routing key. Essentially, this will route the message to the demo
queue that may be created in the client.
@Configuration
@SpringBootApplication
public class AmpqApplicationContext implements CommandLineRunner {
private static final Logger logger = LoggerFactory.getLogger(AmpqApplicationContext.class);
@Autowired
private RabbitTemplate rabbitTemplate;
@Override
public void run(String... strings) throws Exception {
ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);
Runnable task = new Runnable() {
@Override
public void run() {
logger.info("Sending an event...");
rabbitTemplate.convertAndSend("demo", "Hello World");
}
};
scheduledExecutorService.scheduleAtFixedRate(task, 0, 2, TimeUnit.SECONDS);
}
public static void main(String[] args) {
SpringApplication.run(AmpqApplicationContext.class, args);
}
}
Consumer
The consumer declares a queue named demo
.
@Configuration
@SpringBootApplication
public class AmqpClientApplicationContext {
private static final Logger logger = LoggerFactory.getLogger(AmqpClientApplicationContext.class);
@Bean
public org.springframework.amqp.core.Queue demoQueue() {
return new Queue("demo");
}
public static void main(String[] args) {
SpringApplication.run(AmqpClientApplicationContext.class, args);
}
}
The actual listener is declared as a separate Spring @Component
.
Beside that, a listening method is annotated via @RabbitListener
that
will process the received messages.
@Component
public class Listener {
@RabbitListener(queues = "demo")
public void onMessage(String data) {
logger.info(data);
}
}