首页 > 解决方案 > Spring Cloud Stream Reactive,如何为生产者设置路由键

问题描述

Spring Cloud Stream 允许我们使用应用程序配置设置路由键,例如:

cloud.stream:
    default:
      contentType: "application/json"

    rabbit.bindings:
      output-resync-events:
        producer:
          prefix: "xxx."
          routing-key-expression: '''command.service'''

    bindings:
      output-resync-events:
        destination: "resync-requests"

但我需要routing-key为每条消息发送动态设置。

我知道,BinderAwareChannelResolver但似乎这只允许您创建一个新的Exchange本身,这不是预期的结果。

我想使用相同TopicExchange但不同routing-key的s。

此外,是否可以使用 Spring Cloud Stream 的反应式 API 来实现这一点?

标签: springspring-cloud-stream

解决方案


它使用 SPEL,因此您可以像这样在运行时设置它: messagingConfig.dataCopiedChannel().send(MessageBuilder.fromMessage(message).setHeader("type", "key-stuff").build()); messagingConfig 是您的接口,用于将绑定注入到类中以发送消息。

然后,您将 application.properties 配置为如下所示 spring.cloud.stream.bindings.data-copied.destination=data.topic.exchange spring.cloud.stream.rabbit.bindings.data-copied.producer.routing-key-expression=headers.type

这会将其发送到 data.topic.exchange 并带有“key-stuff”的路由键。


推荐阅读