簡體   English   中英

Active MQ + Spring 3.0-請求/響應實現-示例程序得到響應,但消息使用者計數上升且一直在等待

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

我正在嘗試示例項目以實現Spring 3 + Active MQ請求/響應同步。.我創建了一個Spring配置文件,一個消息生產者,它將消息放入隊列中,消息使用者使用消息並返回響應...

我正在得到響應...但是我的示例程序似乎沒有結束...當我檢查Apache Active MQ Admin控制台時,我發現每次運行測試類時,消費者數量都在不斷增加...我必須在eclipse中手動終止它,以便在管理控制台中減少計數...

我在這里提到了這個線程- 堆棧溢出線程 -有人遇到過同樣的問題。.但是看來我已經有了該解決方案,但仍然看不到我的問題已解決

我也在這里這里提到創建我的解決方案

所以這是我的代碼

    <!-- 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" />

請求者類別

@Component

公共類請求者{

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";
    }
}

}

消息偵聽器類

@Component

公共類TestMessageListener實現MessageListener {

@Autowired
private WorkerClient WorkerClient;

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

}

}

工人客戶班

@Component

公共類WorkerClient實現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");
}

最后的測試課

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);

}

}

那么,如何解決消息使用者返回並測試類結束的問題? 請幫忙....

基本上,問題在於應用程序上下文仍然有效,這可能是因為JMS偵聽器容器傳播了線程。 解決方法是在main方法的末尾顯式調用ApplicationContext.close(),這應導致所有bean(包括JMS偵聽器)的有序關閉。

更好的解決方法是使用Spring Test Support,它將負責初始化和關閉應用程序上下文,而不需要您明確地進行操作。

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

    @Autowired OrderService orderService;

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

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM