【问题标题】:Tell Jackson2JsonMessageConverter to use my own class in Amqp.inboundAdapter告诉 Jackson2JsonMessageConverter 在 Amqp.inboundAdapter 中使用我自己的类
【发布时间】:2020-10-06 20:18:19
【问题描述】:

鉴于我有 IntegrationFlow 和 AMQP 队列的入站适配器:

@Bean
public IntegrationFlow readMessagesFlow(
        ConnectionFactory rabbitConnectionFactory,
        ObjectMapper jacksonObjectMapper) {
    return IntegrationFlows.from(
            Amqp.inboundAdapter(rabbitConnectionFactory, QUEUE)
                    .messageConverter(new Jackson2JsonMessageConverter(jacksonObjectMapper))
    )
            .log(INFO, AMQP_LOGGER_CATEGORY)
            .get();
}

当某些外部系统发送带有 JSON 正文的消息时,我发现他们使用 __TypeId__=THEIR_INTERNAL_CLASS

我想将 JSON 正文映射到我自己的类。

目前,它在ClassCastException 上失败,因为THEIR_INTERNAL_CLASS 不可用。

我如何告诉Jackson2JsonMessageConverter 使用我自己的类?

【问题讨论】:

    标签: spring-integration spring-amqp spring-integration-dsl spring-integration-amqp


    【解决方案1】:

    看这个转换器的方法:

    /**
     * Set the precedence for evaluating type information in message properties.
     * When using {@code @RabbitListener} at the method level, the framework attempts
     * to determine the target type for payload conversion from the method signature.
     * If so, this type is provided in the
     * {@link MessageProperties#getInferredArgumentType() inferredArgumentType}
     * message property.
     * <p> By default, if the type is concrete (not abstract, not an interface), this will
     * be used ahead of type information provided in the {@code __TypeId__} and
     * associated headers provided by the sender.
     * <p> If you wish to force the use of the  {@code __TypeId__} and associated headers
     * (such as when the actual type is a subclass of the method argument type),
     * set the precedence to {@link Jackson2JavaTypeMapper.TypePrecedence#TYPE_ID}.
     * @param typePrecedence the precedence.
     * @see DefaultJackson2JavaTypeMapper#setTypePrecedence(Jackson2JavaTypeMapper.TypePrecedence)
     */
    public void setTypePrecedence(Jackson2JavaTypeMapper.TypePrecedence typePrecedence) {
    

    这里是关于此事的文档:https://docs.spring.io/spring-amqp/docs/2.2.11.RELEASE/reference/html/#json-message-converter

    【讨论】:

      【解决方案2】:

      这是一种方法:

      Jackson2JsonMessageConverter messageConverter = new Jackson2JsonMessageConverter(jacksonObjectMapper);
      DefaultClassMapper defaultClassMapper = new DefaultClassMapper();
      defaultClassMapper.setDefaultType(MyOwnClass.class);
      messageConverter.setClassMapper(defaultClassMapper);
      

      Amqp.inboundAdapter中使用messageConverter

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-01-23
        • 2012-03-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-05-12
        • 1970-01-01
        相关资源
        最近更新 更多