JmsTemplate 和 @SendTo() 之间有什么区别?

问题描述

我有两个应用程序,一个是发送请求,另一个是应答,我正在尝试使用 @JmsListener 来实现它。

代码有效:

    public jmstemplate jmstemplate (ConnectionFactory connectionFactory){
        jmstemplate jmstemplate = new jmstemplate();
        jmstemplate.setConnectionFactory(connectionFactory);
        Destination destination = new ActiveMQQueue("replydestination");
        jmstemplate.setDefaultDestination(destination);
        return jmstemplate;
    }

    @JmsListener(destination = "somedestination",containerFactory = "defaultJmsListenerContainerFactory")
    public void receiveMessage (Message message) throws JMSException {
        jmstemplate.send(new ActiveMQTextMessage());
    }

但是当更改为 @SendTo("replydestination") 时它停止工作:

    @JmsListener(destination = "somedestination",containerFactory = "defaultJmsListenerContainerFactory")
    @SendTo("replydestination")
    public Message receiveMessage (Message message) throws JMSException {
        return new ActiveMQTextMessage();
    }

帮助我了解原因,我是否可以在不使用 jmstemplate 的情况下进行此集成。

解决方法

JMS 消息应使用来自 javax.jms.Session 的方法或使用如下构建器构建:

@JmsListener(destination = "somedestination",containerFactory = "defaultJmsListenerContainerFactory")
@SendTo("replydestination")
public org.springframework.messaging.Message<String> listen(javax.jms.Message message) {
    org.springframework.messaging.Message<String> reply = MessageBuilder
            .withPayload("MyReply")
            .build();
    return reply;
}
,

这也有效...

@SpringBootApplication
public class So65570932Application {

    public static void main(String[] args) {
        SpringApplication.run(So65570932Application.class,args);
    }

    @JmsListener(destination = "foo")
    @SendTo("bar")
    String listen(String in) {
        System.out.println(in);
        return in.toUpperCase();
    }

    @Bean
    public ApplicationRunner runner(JmsTemplate template) {
        return args -> {
            template.convertAndSend("foo","baz");
            template.setReceiveTimeout(10_000);
            System.out.println(template.receiveAndConvert("bar"));
        };
    }

}