如何使用 Spring 4 的 JmsTemplate 收听来自 MQ 的消息?

How to listen to messages from an MQ using Spring 4's JmsTemplate?

在 Spring 4 应用程序中使用 WebSphere MQ,监听 MQ 时遇到一些问题(发送消息工作正常)。

这是我的 mvc-dispatcher-servlet.xml 文件的一部分,我在其中指定了 JmsTemplate 的信息:

<bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
        <property name="connectionFactory" ref="appJmsConnectionFactory" />
        <property name="defaultDestinationName" value="MQ.LISTENER.INFO.HERE" />
        <property name="sessionTransacted" value="true" />
    </bean>

这是我的听众 class:

import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.stereotype.Component;

@Component
public class SpringJmsConsumer {
    @Autowired
    private JmsTemplate jmsTemplate;

    private Destination destination;

    public JmsTemplate getJmsTemplate() {
        return jmsTemplate;
    }

    public void setJmsTemplate(JmsTemplate jmsTemplate) {
        this.jmsTemplate = jmsTemplate;
    }

    public Destination getDestination() {
        return destination;
    }

    public void setDestination(Destination destination) {
        this.destination = destination;
    }

    public String receiveMessage() throws JMSException {
        Message message = jmsTemplate.receive(jmsTemplate.getDefaultDestination());
        // TextMessage textMessage = (TextMessage)
        // jmsTemplate.receive(destination);
        System.out.println("The message listened is: " + message.toString());
        return message.toString();
    }
}

我得到的错误:

org.springframework.jms.InvalidDestinationException: JMSMQ0003: The destination is not understood or no longer valid.; nested exception is com.ibm.msg.client.jms.DetailedInvalidDestinationException: JMSMQ0003: The destination is not understood or no longer valid. The queue or topic might have become unavailable, the application might be using an incorrect connection for the queue or topic, or the supplied destination is not of the correct type for this method.

我研究过如何解决这个问题,但无法找到合适的解决方案。

不久前想出了这个问题,但我想我会post这里的答案以帮助将来的其他人。

使用Spring的JMS功能时,监听器需要用@JmsListener

注解

这里说的是receiveMessage()的更新功能:

    @JmsListener(destination = "MQ.LISTENER.INFO.HERE")
    public String receiveMessage(String text) throws JMSException {
        LOGGER.info("Received something!");
        this.jmsTemplate.receiveAndConvert("MQ.LISTENER.INFO.HERE");
        LOGGER.info("Received message from MQ.LISTENER.INFO.HERE: ");
        return "Acknowledgement from receiveMessage";
    }

记住是回调函数!