弹簧 Jms 模板 - 添加自定义属性

2022-09-03 12:12:51

我正在使用Spring API和(版本:)将消息发布到ActiveMQ主题,如下面的代码所示。JmsTemplateMappingJackson2MessageConverterspring-jms-4.3.4.RELEASE.jar

主题发布者类:

@Component
public class TopicPublisher {

    @Autowired
    private JmsTemplate jmsTemplate;

    @Autowired
    private MessageConverter messageConverter;

    public void send() {
        Product product = new Product();
        product.setName("abcd");
        product.setPrice(10);

        jmsTemplate.setMessageConverter(messageConverter);
        jmsTemplate.convertAndSend("product.topic", product);
    }
}

MappingJackson2MessageConverter 类:

@Configuration
public class JMSTextMessageConverter {

    @Bean
    public MessageConverter jacksonJmsMessageConverter() {
        MappingJackson2MessageConverter mappingJackson2MessageConverter 
             = new MappingJackson2MessageConverter();
        mappingJackson2MessageConverter.setTargetType(MessageType.TEXT);
        mappingJackson2MessageConverter.setTypeIdPropertyName("_type");
        return mappingJackson2MessageConverter;
    }   
}

现在,我想为发布到主题的 JMS 消息设置几个自定义标头。我用谷歌搜索,找不到任何这样做的例子。你能帮忙吗?


答案 1

您可以通过发送来使用方法从 添加自定义属性,如下所示:convertAndSendJmsTemplateMessagePostProcessor

jmsTemplate.convertAndSend("product.topic", product, new MessagePostProcessor() {
        @Override
        public Message postProcessMessage(Message message) throws JMSException {
            message.setStringProperty("my_property", "my_value");
            return message;
        }
    });

答案 2

试试下面这样:

@SendTo("product.topic")
public Message<Product> send() {
    Product product = new Product();
    product.setName("abcd");
    product.setPrice(10);

    return MessageBuilder
            .withPayload(product)
            .setHeader("code", 1234) // custom header name and value
            .build();
}

参考资料: https://spring.io/blog/2014/04/30/spring-4-1-s-upcoming-jms-improvements


推荐