Simple Java RabbitMQ Example with Spring

In this example we will create two Queues and we will send JSON and Java Objects.

For this we will create a maven project and we will add those dependecies :

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-amqp</artifactId>
            <version>1.5.3.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-mapper-asl</artifactId>
            <version>1.9.13</version>
        </dependency>

you can remove jackson-mapper-asl dependency if you want to use Java Objects.

The project structure :

Simple Java RabbitMQ Example with Spring project structure

the application.yaml contains rabbitMQ settings:

spring:
  rabbitmq:
    port : 5672
    username : "test"
    password : "test"
    host : "192.168.1.77"

we will write the Application class :

@SpringBootApplication
@ComponentScan("org.newtutorials.rabbitmq")
@EnableScheduling
public class Application {
    public static void main(String[] args) throws InterruptedException {
        SpringApplication.run(Application.class, args);
    }
}

We need @Component scan because all spring components are located on different package

also we enabled scheduling with @EnableScheduling

after that we need to write the message class :

 

public class SimpleMessage implements Serializable{
    private Long messageId;
    private String theMessage;
    private Integer step;

it is time to create the common rabbitMQ configuration class :

@Configuration
public class RabbitConfiguration {

    public static final String JSON_QUEUE_NAME = "jsonQueue";
    public static final String SERIALIZER_QUEUE_NAME = "serializerQueue";

    @Value("${spring.rabbitmq.host:#{null}}")
    String host;
    @Value("${spring.rabbitmq.port:#{null}}")
    Integer port;
    @Value("${spring.rabbitmq.username:#{null}}")
    String username;
    @Value("${spring.rabbitmq.password:#{null}}")
    String password;

    @Bean
    public ConnectionFactory connectionFactory() {
        CachingConnectionFactory connectionFactory = new CachingConnectionFactory(
                host, port);
        connectionFactory.setUsername(username);
        connectionFactory.setPassword(password);
        connectionFactory.setConnectionTimeout(100);
        return connectionFactory;
    }

And the Serializer configuration class :

@Configuration
public class SerializerRabbitConfiguration {

    public static final String SERIALIZER_QUEUE_NAME = "serializerQueue";

    @Bean
    public RabbitTemplate rabbitTemplateSerialize(ConnectionFactory connectionFactory) {
        RabbitTemplate template = new RabbitTemplate(connectionFactory);
        template.setMessageConverter(new SerializerMessageConverter());
        return template;
    }


    @Bean
    public Queue serializerQueue() {
        Map<String, Object> args = new HashMap<String, Object>();
        return new Queue(SERIALIZER_QUEUE_NAME, true, false, false, args);
    }


    @Bean
    SimpleMessageListenerContainer serializerListenerContainer(ConnectionFactory connectionFactory, MessageListenerAdapter serializerMessageListenerAdapter, Queue serializerQueue) {
        SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        container.setQueues(serializerQueue);
        container.setMessageListener(serializerMessageListenerAdapter);
        return container;
    }

    @Bean
    MessageListenerAdapter serializerMessageListenerAdapter(MessageReceiver serializerMessageListener) {
        MessageListenerAdapter receiveMessage = new MessageListenerAdapter(serializerMessageListener, "receiveMessage");
        receiveMessage.setMessageConverter(new SerializerMessageConverter());
        return receiveMessage;
    }

    @Bean
    MessageReceiver serializerMessageListener() {
        return new MessageReceiver(SERIALIZER_QUEUE_NAME);
    }

}

then the JSON Configuration class:

@Configuration
public class JsonRabbitConfiguration {

    public static final String JSON_QUEUE_NAME = "jsonQueue";


    @Bean
    @Autowired
    public RabbitTemplate rabbitTemplateJson(ConnectionFactory connectionFactory) {
        RabbitTemplate template = new RabbitTemplate(connectionFactory);
        template.setMessageConverter(new JsonMessageConverter());
        return template;
    }

    @Bean
    public Queue jsonQueue() {
        Map<String, Object> args = new HashMap<String, Object>();
//        args.put("x-message-ttl", 60000);
        return new Queue(JSON_QUEUE_NAME, true, false, false, args);
    }

    @Bean
    SimpleMessageListenerContainer jsonListenerContainer(ConnectionFactory connectionFactory, MessageListenerAdapter jsonMessageListenerAdapter, Queue jsonQueue) {
        SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        container.setQueues(jsonQueue);
        container.setMessageListener(jsonMessageListenerAdapter);
        return container;
    }

    @Bean
    MessageListenerAdapter jsonMessageListenerAdapter(MessageReceiver jsonMessageListener) {
        MessageListenerAdapter receiveMessage = new MessageListenerAdapter(jsonMessageListener, "receiveMessage");
        receiveMessage.setMessageConverter(new JsonMessageConverter());
        return receiveMessage;
    }
    @Bean
    MessageReceiver jsonMessageListener() {
        return new MessageReceiver(JSON_QUEUE_NAME);
    }

}

 

the message receiver class :

@Component
public class MessageReceiver {

    private String queueName;

    public MessageReceiver() {
    }

    public MessageReceiver(String queueName) {
        this.queueName = queueName;
    }

    public void receiveMessage(SimpleMessage simpleMessage) {
        System.out.println("received["+queueName+"] : " + simpleMessage);
    }
}

now we have the rabbitMQ ready to be tested , lets create a Scheduled method to send messages to queues :

@Component
public class ScheduledTasks {

    @Autowired
    RabbitTemplate rabbitTemplateJson;

    @Autowired
    RabbitTemplate rabbitTemplateSerialize;

    @Scheduled(cron = "*/02 * * * * *")
    public void runIt() {
        SimpleMessage simpleMessage;
        simpleMessage = new SimpleMessage(System.currentTimeMillis(), "Json Message", 0);
        System.out.println("sending : " + simpleMessage);
        rabbitTemplateJson.convertAndSend(JsonRabbitConfiguration.JSON_QUEUE_NAME, simpleMessage);
        simpleMessage = new SimpleMessage(System.currentTimeMillis(), "Serializer Message", 0);
        System.out.println("sending : " + simpleMessage);
        rabbitTemplateSerialize.convertAndSend(SerializerRabbitConfiguration.SERIALIZER_QUEUE_NAME, simpleMessage);
    }
}

lets run the application , we will see that the messages will be sent to queue and consumed bu receiver:

sending : SimpleMessage{messageId=1497020988001, theMessage='Json Message', step=0}
sending : SimpleMessage{messageId=1497020988111, theMessage='Serializer Message', step=0}
received[serializerQueue] : SimpleMessage{messageId=1497020988111, theMessage='Serializer Message', step=0}
received[jsonQueue] : SimpleMessage{messageId=1497020988001, theMessage='Json Message', step=0}
sending : SimpleMessage{messageId=1497020990003, theMessage='Json Message', step=0}
sending : SimpleMessage{messageId=1497020990004, theMessage='Serializer Message', step=0}
received[jsonQueue] : SimpleMessage{messageId=1497020990003, theMessage='Json Message', step=0}
received[serializerQueue] : SimpleMessage{messageId=1497020990004, theMessage='Serializer Message', step=0}

 

Download the code from github

Category: Java Tutorials