出站消息转换

Spring AMQP 1.4 引入了 ContentTypeDelegatingMessageConverter,它根据传入的内容类型消息属性选择实际的转换器。 这可用于入站端点。

从 Spring Integration 4.3 版本开始,你也可以在出站端点上使用 ContentTypeDelegatingMessageConverter,其中 contentType 消息头指定使用哪个转换器。

以下示例配置了一个 ContentTypeDelegatingMessageConverter,默认转换器是 SimpleMessageConverter (处理 Java 序列化和纯文本),以及一个 JSON 转换器:

<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 转换器。

这适用于出站通道适配器和网关。

从 5.0 版本开始,添加到出站消息的 MessageProperties 中的消息头永远不会被映射的消息头覆盖(默认情况下)。 以前,只有当消息转换器是 ContentTypeDelegatingMessageConverter 时才如此(在这种情况下,消息头会首先被映射,以便选择正确的转换器)。 对于其他转换器,例如 SimpleMessageConverter,映射的消息头会覆盖转换器添加的任何消息头。 这会导致问题,当出站消息有一些遗留的 contentType 消息头(可能来自入站通道适配器)并且正确的出站 contentType 被错误地覆盖时。 解决方法是使用消息头过滤器在将消息发送到出站端点之前删除该消息头。 但是,在某些情况下,需要以前的行为——例如,当 String 负载包含 JSON 时,SimpleMessageConverter 不知道内容并将 contentType 消息属性设置为 text/plain,但你的应用程序希望通过设置发送到出站端点的消息的 contentType 消息头将其覆盖为 application/jsonObjectToJsonTransformer 正是这样做的(默认情况下)。 现在出站通道适配器和网关(以及 AMQP 支持的通道)上有一个名为 headersMappedLast 的属性。 将其设置为 true 会恢复覆盖转换器添加的属性的行为。 从 5.1.9 版本开始,为 AmqpInboundGateway 提供了类似的 replyHeadersMappedLast,当我们生成回复并希望覆盖转换器填充的消息头时。 有关更多信息,请参阅其 JavaDocs。