jmstemplate和@sendto()有什么区别?

bxgwgixi  于 2021-06-27  发布在  Java
关注(0)|答案(2)|浏览(354)

我有两个应用程序,一个是发送请求,另一个是应答,我试图用 @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 .

vyu0f0g1

vyu0f0g11#

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

jaql4c8m2#

这也行。。。

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

}

相关问题