Spring Boot with In-memory ActiveMQ

Spring Boot with In-memory ActiveMQ

The in-memory ActiveMQ can be used to quickly test any message broker specific functionality when we don’t have an external message broker readily available.

In the given example we will submit a string to a RESTful web service which will save the message string in the queue on message broker. Then we will implement a listener to read the message from the queue and display it on console.

Setup

First ensure you have the following dependencies selected from Spring Boot starter while setting up your Spring Boot application.

  • Spring Web
  • Spring for Apache ActiveMQ 5

In application.properties resource file add the following configurations.

spring.activemq.in-memory=true
spring.activemq.pool.enabled=false

Now create a new configuration class to define a queue.

@EnableJms
@Configuration
public class MessageQueueConfig {

	 @Bean
	 public Queue queue() {
	  return new ActiveMQQueue("demo.queue");
	 }
}

Publish Message

Create a RESTful web service by defining a controller class and push the message onto the queue using path variable.

@RestController
public class PersonController {

    @Autowired
    private JmsTemplate jmsTemplate;

    @Autowired
    private Queue queue;

    @GetMapping("/{payload}")
    public String publish(@PathVariable("payload") final
                          String payload) {

        jmsTemplate.convertAndSend(queue, payload);

        return "Message saved successfully!";
    }
}

Create Listener

Create a Spring component class with a listener method as shown below

@Component
public class MessageListener {

    @JmsListener(destination = "inmemory.queue")
    public void listener(String message) {
        System.out.println("Received Message: " + message);
    }
}

Now you can run the application and submit a request using the following URL:

http://localhost:8080/hello

This request will be serviced by the RESTful web service which will push the “hello” message to the queue. The listener will pick the message and display the following string on the console

Output: hello