【问题标题】:What is the difference beetween JmsTemplate and @SendTo()?JmsTemplate 和@SendTo() 之间有什么区别?
【发布时间】:2021-04-10 17:36:01
【问题描述】:

我有两个应用程序,一个是发送请求,另一个是应答,我正在尝试使用@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 的情况下进行此集成。

【问题讨论】:

  • 您看到任何错误吗? here 报告了类似的问题。

标签: java spring-jms


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    这也有效...

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-05-08
      • 2018-12-23
      • 2010-11-07
      • 2014-07-20
      • 2011-03-01
      • 2013-02-20
      • 2012-01-01
      相关资源
      最近更新 更多