在 Spring Integration 应用程序中,没有用于状态共享的单个 ExecutionContext。相反,正如 Gary Russel 所提到的,每条消息都在其有效负载或标头中携带所有信息。
如果您使用 Spring Integration Java DSL 并希望clientId
通过消息头传输您可以使用enrichHeader
转换器。提供一个HeaderEnricherSpec
,它可以接受一个函数,该函数为指定的标头返回动态确定的值。根据您的用例,这可能如下所示:
return IntegrationFlows
.from(/*ftp source*/)
.enrichHeaders(e -> e.headerFunction("clientId", this::deriveClientId))
./*split, aggregate, etc the file according to clientId*/
,其中deriveClientId
方法可能是一种:
private String deriveClientId(Message<File> fileMessage) {
String fileName = fileMessage.getHeaders().get(FileHeaders.FILENAME, String.class);
String clientId = /*some other logic for deriving clientId from*/fileName;
return clientId;
}
(FILENAME
报头由 FTP 消息源提供)
当您需要访问clientId
下游流中某处的标头时,您可以按照与上述文件名相同的方式进行操作:
String clientId = message.getHeaders().get("clientId", String.class);
但请确保message
仍然包含这样的标题,因为它可能在中间流项目中的某个地方丢失。如果您在某些时候手动构建消息并进一步发送,则很可能会发生这种情况。为了不丢失前面消息中的任何标题,您可以在构建期间复制它们:
Message<PayloadType> newMessage = MessageBuilder
.withPayload(payloadValue)
.copyHeaders(precedingMessage.getHeaders())
.build();
请注意,消息头在 Spring Integration 中是不可变的。这意味着您不能只添加或更改现有消息的标题。您应该创建一条新消息或HeaderEnricher
用于该目的。上面介绍了这两种方法的示例。