简体   繁体   中英

Active MQ + Spring 3.0 - Request/Response Implementation - Sample Program got response But Message Consumer count keps going up and waiting for ever

I am trying sample projects to implement a Spring 3 + Active MQ Request/Response Synchronos.. I created a spring configuration file, a message producer that puts message in a queue and message consumer that consumes the message and returns a response...

I am getting the response back... But my sample program doesnt seem to end... When i check the Apache Active MQ Admin console I see that the NUmber of Consumers count keeps going up every time I run my test class... I got to terminate it manually in eclipse for the count to go down in the admin console...

I referred this thread here - Stack Overflow Thread - Somebody who has faced the same issue.. But looks like I already have that solution in place and still don't see my issue solved

Also I referred here and here to create my solution

So here is my code

    <!-- creates an activemq connection factory using the amq namespace -->

<bean id="jmsConnectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
    <property name="brokerURL" value="tcp://localhost:61616" />
</bean>

<!-- 
<bean id="connectionFactory" class="org.apache.activemq.pool.PooledConnectionFactory"
    init-method="start" destroy-method="stop">
    <property name="connectionFactory" ref="jmsConnectionFactory" />
    <property name="maxConnections" value="100" />
</bean>
 -->

<!-- CachingConnectionFactory Definition, sessionCacheSize property is the 
    number of sessions to cache -->

<bean id="connectionFactory"
    class="org.springframework.jms.connection.CachingConnectionFactory">
    <constructor-arg ref="jmsConnectionFactory" />
    <property name="exceptionListener" ref="jmsExceptionListener" />
    <property name="sessionCacheSize" value="1" />
    <property name="cacheConsumers" value="false" />
    <property name="cacheProducers" value="false" />
</bean>

<!-- JmsTemplate Definition -->
<bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
    <constructor-arg ref="connectionFactory" />

</bean>


<jms:listener-container connection-factory="connectionFactory">
    <jms:listener id="request.queue.listener" destination="test.request"
        ref="testMessageListener" />
</jms:listener-container>

<bean id="WorkerClient" class="com.vzwcorp.legal.eplm.active.mq.framework.WorkerClient" />

Requestor Class

@Component

public class Requestor {

private static final class ProducerConsumer implements
        SessionCallback<Message> {

    private static final int TIMEOUT = 5000;

    private final String msg;

    private final DestinationResolver destinationResolver;

    private final String queue;

    public ProducerConsumer(final String msg, String queue,
            final DestinationResolver destinationResolver) {
        this.msg = msg;
        this.queue = queue;
        this.destinationResolver = destinationResolver;
    }

    public Message doInJms(final Session session) throws JMSException {
        MessageConsumer consumer = null;
        MessageProducer producer = null;
        try {
            final String correlationId = UUID.randomUUID().toString();
            final Destination requestQueue = destinationResolver
                    .resolveDestinationName(session, queue + ".request",
                            false);
            final Destination replyQueue = destinationResolver
                    .resolveDestinationName(session, queue + ".response",
                            false);
            // Create the consumer first!
            consumer = session.createConsumer(replyQueue,
                    "JMSCorrelationID = '" + correlationId + "'");
            final TextMessage textMessage = session.createTextMessage(msg);
            textMessage.setJMSCorrelationID(correlationId);
            textMessage.setJMSReplyTo(replyQueue);
            // Send the request second!
            producer = session.createProducer(requestQueue);
            producer.send(requestQueue, textMessage);
            // Block on receiving the response with a timeout
            return consumer.receive(TIMEOUT);
        } finally {
            // Don't forget to close your resources
            JmsUtils.closeMessageConsumer(consumer);
            JmsUtils.closeMessageProducer(producer);
        }
    }
}

private final JmsTemplate jmsTemplate;

@Autowired
public Requestor(final JmsTemplate jmsTemplate) {
    this.jmsTemplate = jmsTemplate;
}

public String request(final String request, String queue) {
    // Must pass true as the second param to start the connection
    TextMessage message = (TextMessage) jmsTemplate.execute(
            new ProducerConsumer(request, queue, jmsTemplate
                    .getDestinationResolver()), true);
    try {
        return message.getText();
    } catch (JMSException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return "exception in requestor";
    }
}

}

Message Listener Class

@Component

public class TestMessageListener implements MessageListener {

@Autowired
private WorkerClient WorkerClient;

@Override
public void onMessage(Message arg0) {
    WorkerClient.delegateToClient(arg0);

}

}

Worker Client Class

@Component

public class WorkerClient implements ApplicationContextAware {

private ApplicationContext ctx;

private JmsTemplate jmsTemplate;

public void delegateToClient(Message arg0) {
    MessageProducer producer = null;
    if (arg0 instanceof TextMessage) {
        try {
            final TextMessage message = (TextMessage) arg0;

            System.out.println("Message received by Listener: "
                    + message.getJMSCorrelationID() + " - "
                    + message.getText());

            jmsTemplate.setDefaultDestination(message.getJMSReplyTo());

            Session session = jmsTemplate.getConnectionFactory()
                    .createConnection()
                    .createSession(false, Session.AUTO_ACKNOWLEDGE);
            producer = session.createProducer(message.getJMSReplyTo());
            final TextMessage textMessage = session
                    .createTextMessage("I did it at last");
            textMessage.setJMSCorrelationID(message.getJMSCorrelationID());
            textMessage.setJMSReplyTo(message.getJMSReplyTo());
            producer.send(message.getJMSReplyTo(), textMessage);

        } catch (Exception e) {
            e.printStackTrace();

        } finally {
            JmsUtils.closeMessageProducer(producer);
        }
    }
}

@Override
public void setApplicationContext(ApplicationContext arg0)
        throws BeansException {
    ctx = arg0;
    this.jmsTemplate = (JmsTemplate) ctx.getBean("jmsTemplate");
}

At Last The test class

public class TestSync {

public static void main(String[] args) {

    ApplicationContext ctx = new ClassPathXmlApplicationContext(
            "activeMQConfiguration.xml");
    OrderService orderService = (OrderService) ctx.getBean("orderService");
    JmsTemplate jmsTemplate = (JmsTemplate) ctx.getBean("jmsTemplate");
     Requestor req = new Requestor(jmsTemplate);
    //CopyOfRequestor req = new CopyOfRequestor(jmsTemplate);
    String response = req.request("Hello World", "test");
    System.out.println(response);

}

}

So how to fix the message consumer returning back and my test class ending? Please Help....

The problem basically is that the application context remains alive probably because of the threads propagated by the JMS listener container. The fix is to explicitly call ApplicationContext.close() at the end of your main method, this should lead to orderly shutdown of all the beans (including the JMS listener).

A better fix is to use Spring Test Support, which will take care of initializing and shutting down the application context instead of you needing to do it explicitly.

@RunWith(SpringJUnit4Runner.class)
@ContextConfiguration(...)
public class TestSync{

    @Autowired OrderService orderService;

    @Test
    public void testJMS(){
        ...
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM