Synchronous Request Response with ActiveMQ and Spring

35 thoughts on “Synchronous Request Response with ActiveMQ and Spring”

  1. Okay, this is great…EXCEPT, that the connection.start() has to be called in order to consume messages. The JMSTemplate from Spring specifically doesn’t call connection.start() when using a ProducerCallback. Thus, I’m not sure how your code would work as displayed. If you wrap the ProducerCallback in a SessionCallback, and then call the template.execute(sessionCallback(),true) then all is fine.


      1. Why does the above code not work for me. I can see the producer populating the queue but it never sends to the consumer in other words the consumer queue is always empty. However if the producer and consumer use the same queue it seems to work fine.Please help as i am stuck with this for ages.

      2. Sorry Jigar. I wrote this post over 5 years ago. I don’t think I will be able to help. I would recommend asking on the ActiveMQ mailer or irc.

  2. Hi, Thanks very much for the article, I’ve also just recently tried to implemented request-reply using Spring in a similar manner to your example except I am using Sonic MQ as my JMS Provider.

    Sonic have asked that I create a temporary destination per session for best performance and exactly as you discussed this doesn’t seem feasible in Spring so I’m reverting to writing the code by hand and not using Spring! I am assuming that when you talk about having a predefined response queue you mean it has been administratively setup and is shared by all threads/sessions. I therefore wonder in your example how you cope with the scenario where multiple threads are calling request() and hence there are a number of responses on the predefined response queue? How do you correlate that a particular response is associated with a particular request? I would have thought you’d need a message selector?


    1. Exactly right, you use a selector coupled with the JMSCorrelationId. If you look through the code sample you can see where it is set and where the selector is set. Apologies if that wasn’t clear enough.

  3. Benjamin,
    Do you know why this runs but doesn’t publish?

    public String request(final String request) throws JMSException {
    ProducerConsumer prodCons = new ProducerConsumer(request,jmsTemplate);
    Message respJmsMsg = jmsTemplate.execute(prodCons,true);
    String respStrMsg = ((TextMessage)respJmsMsg).getText();
    return respStrMsg;

    public ProducerConsumer(final String msg, final JmsTemplate jmsTemplate) {
    this.msg = msg;
    this.jmsTemplate = jmsTemplate;

    public Message doInJms(Session session) throws JMSException {
    MessageProducer msgProd=null;
    MessageConsumer msgCons=null;
    String destName = jmsTemplate.getDefaultDestinationName();
    DestinationResolver destResolver = jmsTemplate.getDestinationResolver();
    Destination dest = destResolver.resolveDestinationName(session, destName, true);
    msgProd = session.createProducer(dest);
    TextMessage txtMsg = session.createTextMessage(msg);
    Destination tempReplyQ = session.createTemporaryQueue();
    final String correlationId = UUID.randomUUID().toString();
    logger.debug(String.format(“Send: %s; On: %s; With ReplyTo: %s”,txtMsg, dest,

    msgCons = session.createConsumer(tempReplyQ);
    Message respJmsMsg = msgCons.receive(TIMEOUT);
    logger.debug(String.format(“RecievedSynchReply: %s; On ReplyTo: %s”,respJmsMsg, tempReplyQ));
    return respJmsMsg;

      1. Thx Benjamin any ways.

        What it was that the on the receiver ( receiver not shown in the code was missing destination-type=”topic”; default destination-type is queue). So messages were being written to a topic with a particular name while the receiver was listening to a queue of the same name and hence not getting it which I falsely concluded as ‘messages not being published’.

        You may delete this post.

  4. can you please let me know how to run this code that you have given. I am new to jms spring and trying to correlate request/response message but i was unable to run this code. please help.

      1. thank you for the response. I am using websphere mq with permanent queues.
        in the message creator i have setreply to the response queue will your code work if i replace with permanent qeueu setting replyto to the response queue.
        i am trying to correlate sychronous request-response with websphere mq using permanent queue since websphere mq doesnt support temporary queue. i aprpeciate your response.


      2. I’m not quite sure what you are asking (please check for spelling at least before sending). However, if you are asking can you use permanent queues I don’t see why not. The best way to find out of course is to code and test it.

  5. Hi Benjamin,

    I have run into a problem where my Active MQ listener seems to receive XX no of messages where XX is equal to number of concurrent consumers.

    ActiveMQ consumer stops receving messages

    I am using Spring 3 and Active MQ 5.3.0.

    The problem that I am facing is that it looks like each consumer receives 1 message.
    I have set the concurrent consumers to 30 and maximum concurrent consumers to 100.

    I have a TaskListener(message listener) which receives a message to run process A. In
    process A I need to trigger sub-processes. Trigerring a sub-process involves sending
    a message to TaskListener to run sub-process A1…In Process A class I am polling/waiting
    until all the sub-processes complete. Looks like I am limited to running to only 30
    sub-processes(same as the concurrent consumers).

    The JMS set up is as follows:


    What am I overlooking ? Please advice.

    1. Thats a great question, I feel like it sounds familiar but I haven’t touched AMQ in a year now. I would suggest you post on the mailer or in the irc channel. The guys there are very good and very helpful. Best of luck.

  6. >> Unfortunately, CachingConnectionFactory caches MessageConsumers based on a hash
    >> key which contains the selector among other values
    This can be disabled with CachingConnectionFactory’s setCacheConsumers(false). This fixes the consumer ‘leak’, and has no noticable performance-hit over using cached consumers.

    I’ve been using ActiveMQ 5.5 while testing this. It seems like the only thing that really helps with performance is using an existing response-queue, instead of creating new ones for each request.

  7. Hi,

    This blog post have been very helpful because “it just makes more sense to use a synchronous request/response” as you said ;o)

    By the way, I am not sure I have understood how to use the permanent response queue. Does it mean that the request queue listener have to use a queue sender to send a response to the initial requester (that is waiting an answer on the response queue)? Or there is a smarter way to code that? How the queue listener should be coded to use the response queue?


    1. Yes the responder sends the response on a known queue with a correlation id. The requester listens on the known response queue for a message with that correlation id. Does that help?

      1. It helps! But One more questions : does it works for several requesters (concurrent process) using the same queue with a single responder? How does each requester manage to get its correct correlation id without removing the other ones from the queue?

      2. Yes, when you subscribe to the reply queue you do so with a selector for that correlation id. ActiveMQ takes care of the rest. You can see all this in the code samples. I promise it works 😉

  8. Hi Benjamin

    I tried this and it works great in my system… I am getting a response in sync mode.. But I see that the message consumers count keeps on increasing for ever… I tried switching to active mq pooled connection factory too…. that doesnt seem to solve my issue…Can you please advise…

  9. guys…

    can’t you simply use CachingConnectionFactory.setCacheConsumers(false); to fix the caching issue without using ActiveMQ’s pool objects? (keep it in spring).

    Also, this code seems like it is simply a workaround for a Spring Bug. Right?

    we “SHOULD” be able to do jmstemplate.send() then jmstemplate.receive() without losing synchronous message response?

    Thanks for this blog post. It certainly did help.

    By the way, if you are interested…I changed the code such that the constructor took in a “MessageCreator” object. Helps when sending different types of messages (Text, Properties, Object…etc).



    1. Hey James,

      Thanks for the comment. Its been now over 3 years since I wrote this I haven’t touched the system I was working on at the time in almost as long. For that reason I can’t really answer your question with any certainty but I’m glad the post helped and feel free to follow up here if you find out any further information.



  10. Hi Benjamin,

    When the message already arrives in Queue before consumer invokes receive, we always miss the message. Is this default JMS behavior ? Isn’t the message supposed to stay in the Queue forever until someone grab it ?


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s