August 19, 2017

Scheduled Message Consumer on ActiveMQ with Spring DMLC and Quartz

In this post I show how to schedule a task to start and stop a JMS MessageListener (Consumer) on ActiveMQ on a predefine date and time with Quartz Scheduler and Spring DefaultMessageListenerContainer (DMLC). From the other side (Producer) if you want to see how the delay and schedule message delivery works, I suggest the ActiveMQ scheduler built-in.

Stack

ActiveMQ 5.11.1
JDK 1.8
Maven 3.2
Spring 3.0.5.RELEASE
Quartz Scheduler 1.5.2

Source

SUBVERSION
svn co https://github.com/giuseppeurso-eu/activemq/trunk activemq-samples
GIT
git clone https://github.com/giuseppeurso-eu/activemq

 

Consumer

This is the MessageListener implementation. The onMessage() method is responsible for the consumption of messages. I create two methods startConsumption() and stopConsumption() to run start/stop on the DMLC Spring object. The instance of DMLC will be defined later via dependency-injection in the beans XML file.

 

Producer

A simple class which make use of Spring JmsTemplate to publish a number of messages. Destinations[ ] could be useful in case of sending on multiple queues.

 

Spring XML configuration

Here is the Spring beans definition.Pay attention to the autoStartup property which is false in the sampleDMLC bean. I will use the Quartz Scheduer to define two jobs which will be responsible for starting and stopping of the message consumer. In order to define the job details I use MethodInvokingJobDetailFactoryBean and SchedulerFactoryBean. The two jobs have a different targetMethod to start/stop message consumption but the same targetObject which refers to the same consumer. The consumer bean includes a property sampleListener injected via Spring which creates an instance of DMLC.

In this example, I use a simple cron expression to start message consumption in a given time and stop it after 15 seconds.

 

Run Test

Finally a simple JUnit test class ScheduledConsumerTest, to simulate a use case. This class sends a message on a sample queue and waits until 20 seconds with a Thread.sleep for the job executions.

giuseppe-urso-activemq-scheduled-message-consumer-01

 

giuseppe-urso-activemq-scheduled-message-consumer-02

Related posts

2 Comments

    1. Giuseppe

      The Quartz scheduler performs asynchronous actions and knows nothing of what happens while the messages are consumed. If you need to do something when consumption is finished, you should make programmatically in the Consumer class.
      Otherwise you can play with the cronExpression attribute which is responsible for starting and stopping of the message consuming:

        http://www.quartz-scheduler.org/api/2.1.7/org/quartz/CronTrigger.html?is-external=true#setCronExpression-org.quartz.CronExpression-

Leave a Reply

Your email address will not be published.