DEV Community

Cover image for Apache Camel #3 - RabbitMq
Djordje Bajic
Djordje Bajic

Posted on • Updated on

Apache Camel #3 - RabbitMq

Hello there again!

It passed 2 months since my last article, so I decided to write a new one.

Today we will focus on RabbitMq and what we can do with it using Camel.

Dependencies

Maven repository -> Camel RabbitMq

Connection to RabbitMq

When using SpringBoot:

  1. Create a class with @Configuration annotation.
  2. Create a method which will return ConnectionFactory and annotate it with @Bean.
  3. Instance a connection factory and set properties.
@Bean
public ConnectionFactory rabbitConnectionFactory() {
    ConnectionFactory connectionFactory = new ConnectionFactory();
    connectionFactory.setHost("localhost);
    connectionFactory.setPort(5672);
    connectionFactory.setUsername("Username");
    connectionFactory.setPassword("Password);

    return connectionFactory;
}
Enter fullscreen mode Exit fullscreen mode

*note: You can use application properties to connect to the server.

If you are using pure Camel:

Using RabbitMq

Now that we successfully connected to RabbitMq it's time to start consuming/producing messages to queue/exchange.

Camel RabbitMq component documentation.

Consuming Message from the queue:

  1. We will set the rabbitMq component to fetch from the queue which is bind to exchange.
  2. Log message body received.

public void configure() {

from("rabbitmq:exchangeA?queue=QueueA&declare=true")
.routeId("RabbiqMqConsumer")
.log("Message received: ${body}");
Enter fullscreen mode Exit fullscreen mode

Producing Message to exchange:

  1. We will create a route.
  2. Set message body.
  3. Send a message to the exchange.

public void configure() {

 from("timer:fooo?period=10000")
 .routeId("RabbiqMqProducer)
 .setBody().constant("{\"foo\":\"bar\"}")
 .log("Message to be sent: ${body}")
 .to("rabbitmq:exchangeB");
Enter fullscreen mode Exit fullscreen mode

Aand that's all folks, if anyone have some question, feel free to ask me via DM or just leave a comment.

Top comments (0)