在Spring集成應用中存在的狀態共享沒有單一的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集成不變。這意味着您不能只添加或更改現有消息的標題。您應該創建一條新消息或爲此目的使用HeaderEnricher
。上面介紹了兩種方法的例子。