无法将Message对象从RabbitMQ转换为Java类

时间:2018-11-29 19:50:30

标签: java spring rabbitmq spring-amqp

我创建了RabbitListener来从RabbitMQ队列中获取消息。

我的RabbitMQ消息:

preset-env

我的监听器方法:

{
  "presets": [
    ["@babel/preset-env", {
      "targets": { "electron": "3.0.10" },
      "useBuiltIns": "usage"
    }],
    "@babel/preset-react",
    "@babel/preset-flow"
  ],
  "plugins": [
    "@babel/plugin-transform-flow-strip-types",
    "add-module-exports",
    "@babel/plugin-proposal-export-default-from",
    ["@babel/plugin-proposal-optional-chaining", { "loose": false }],
    "@babel/plugin-proposal-do-expressions",
    "@babel/plugin-proposal-export-namespace-from",
    "@babel/plugin-proposal-class-properties",
    "@babel/plugin-transform-classes",
  ]
}

Bean配置:     @豆角,扁豆     公共ObjectMapper objectMapper(){         返回新的ObjectMapper();     }

Properties  
priority:   0
delivery_mode:  2
headers:    
__TypeId__: com.kmb.bank.models.Transfer
content_encoding:   UTF-8
content_type:   application/json
Payload
356 bytes
Encoding: string


{"userAccountNumber":"1111444422221111","title":"123","recipientName":"123","recipientAccountNumber":"1234123412341234","amount":123.0,"localDateTime":{"nano":526106200,"year":2018,"monthValue":11,"dayOfMonth":29,"hour":20,"minute":43,"second":0,"month":"NOVEMBER","dayOfWeek":"THURSDAY","dayOfYear":333,"chronology":{"id":"ISO","calendarType":"iso8601"}}}

和转移课程:

@Autowired
private Jackson2JsonMessageConverter jackson2JsonMessageConverter;

@RabbitListener(queues = "kolejka")
public void listen(Message message) {
    try {
        Transfer transfer = (Transfer) jackson2JsonMessageConverter.fromMessage(message);
        log.info(transfer);
    } catch (Exception e) {
        log.debug("Error thrown while listening + " + e.getMessage());
    }

}

不幸的是,从Message转换为Transfer传输对象时抛出了异常。

@Bean
public Jackson2JsonMessageConverter jackson2JsonMessageConverter() {
    return new Jackson2JsonMessageConverter(objectMapper());
}

整个消息日志: https://pastebin.com/raw/47Lq7dYD

1 个答案:

答案 0 :(得分:3)

您必须在接收方Jackson2JsonMessageConverter的类型映射器中设置类型映射,以映射到其他类。

通常,发送者会将其类映射到令牌,例如transfer,接收方会将其映射到其Transfer版本。

或者,如果您使用public void listen(Transfer transfer),并且将转换器连接到侦听器容器工厂,则框架将从参数中推断类型。

如果它是Spring Boot应用程序,则该连接将自动进行。