在spring boot中转换activemq msg

时间:2018-05-03 22:37:58

标签: spring spring-boot jms activemq

我正在使用spring boot来解码jms消息

配置

@Bean
public JmsListenerContainerFactory<?> myFactory(ConnectionFactory connectionFactory,
        DefaultJmsListenerContainerFactoryConfigurer configurer) {
    DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory();
    // This provides all boot's default to this factory, including the message
    // converter
    configurer.configure(factory, connectionFactory);
    factory.setMessageConverter(this.jacksonJmsMessageConverter());
    // You could still override some of Boot's default if necessary.
    return factory;
}

@Bean // Serialize message content to json using TextMessage
public MessageConverter jacksonJmsMessageConverter() {
    MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter();
    converter.setTargetType(MessageType.TEXT);

    converter.setObjectMapper(new ObjectMapper());
    return converter;
}

我能够收到消息并解码消息

@JmsListener(destination = "myQueue", containerFactory = "myFactory")
public void receiveMessage(ActiveMQTextMessage msg) throws JMSException, IOException {

    String text = msg.getText();
    ObjectMapper mapper = new ObjectMapper();
    MyObject obj = mapper.readValue(text, MyObject.class);

我的问题是我不想每次都打电话给mapper.readValue(xxx),我更喜欢 在messageconverter bean中配置映射器和转换,我的关键 是从转换器调用msg.getText(),但我如何获得引用 转换器中的msg,或者有更聪明的方法。

1 个答案:

答案 0 :(得分:0)

Spring为您做到了这一点,因为您已经sappagedown MessageConverter factory配置了factory.setMessageConverter(this.jacksonJmsMessageConverter());

所以使用这样的论点:

@JmsListener(destination = "myQueue", containerFactory = "myFactory")
public void receiveMessage(MyObject obj) throws JMSException, IOException {
    //do stuff with obj
}