如需使用最新稳定版本,请使用 Spring Integration 7.0.4spring-doc.cadn.net.cn

出站消息转换

Spring AMQP 1.4 引入了 ContentTypeDelegatingMessageConverter,其中实际的转换器会根据传入消息的内容类型属性进行选择。 这可用于入站端点。spring-doc.cadn.net.cn

从 Spring Integration 4.3 版本开始,您也可以在出站端点使用 ContentTypeDelegatingMessageConverter,并通过 contentType 标头指定所使用的转换器。spring-doc.cadn.net.cn

以下示例配置了一个 ContentTypeDelegatingMessageConverter,默认转换器为 SimpleMessageConverter(用于处理 Java 序列化和纯文本),并搭配一个 JSON 转换器:spring-doc.cadn.net.cn

<amqp:outbound-channel-adapter id="withContentTypeConverter" channel="ctRequestChannel"
                               exchange-name="someExchange"
                               routing-key="someKey"
                               amqp-template="amqpTemplateContentTypeConverter" />

<int:channel id="ctRequestChannel"/>

<rabbit:template id="amqpTemplateContentTypeConverter"
        connection-factory="connectionFactory" message-converter="ctConverter" />

<bean id="ctConverter"
        class="o.s.amqp.support.converter.ContentTypeDelegatingMessageConverter">
    <property name="delegates">
        <map>
            <entry key="application/json">
                <bean class="o.s.amqp.support.converter.Jackson2JsonMessageConverter" />
            </entry>
        </map>
    </property>
</bean>

ctRequestChannel 发送消息并将 contentType 头设置为 application/json,这将导致选择 JSON 转换器。spring-doc.cadn.net.cn

这适用于出站通道适配器和网关。spring-doc.cadn.net.cn

从 5.0 版本开始,添加到出站消息 MessageProperties 的标头默认情况下永远不会被映射的标头覆盖。 在此之前,仅当消息转换器为 ContentTypeDelegatingMessageConverter 时才适用此规则(在这种情况下,会先映射标头以便选择正确的转换器)。 对于其他转换器(例如 SimpleMessageConverter),映射的标头会覆盖由转换器添加的任何标头。 这导致了一些问题:当出站消息带有一些残留的 contentType 标头(可能来自入站通道适配器)时,正确的出站 contentType 会被错误地覆盖。 解决方法是使用标头过滤器在将消息发送到出站端点之前移除该标头。spring-doc.cadn.net.cn

然而,在某些情况下需要之前的行为——例如,当包含 JSON 的 String 有效负载中,SimpleMessageConverter 不了解内容并将 contentType 消息属性设置为 text/plain,但您的应用程序希望通过设置发送到出站端点的消息的 contentType 标头将其覆盖为 application/jsonObjectToJsonTransformer 正是这样做的(默认情况下)。spring-doc.cadn.net.cn

现在,出站通道适配器和网关(以及基于 AMQP 的通道)上有一个名为 headersMappedLast 的属性。 将其设置为 true 可恢复由转换器添加的属性被覆盖的行为。spring-doc.cadn.net.cn

从版本 5.1.9 开始,当生成回复并希望覆盖由转换器填充的头部时,为 replyHeadersMappedLast 提供了类似的 AmqpInboundGateway。 有关更多信息,请参阅其 Javadoc。spring-doc.cadn.net.cn