Warm tip: This article is reproduced from stackoverflow.com, please click
spring spring-integration

Spring-integration: keep a context for a Message throught a chain

发布于 2020-03-27 10:20:42

I am using spring-integration, and I have messages that goes through an int:chain with multiple elements: int:service-activator, int:transformers, etc. In the end, a message is sent to another app's Rest endpoint. There is also an errorHandler that will save any Exception in a text file.

For administration purpose, I would like to keep some information about what happened in the chain (ex: "this DB call returned this", "during this transformation, this rule was applied", etc.). This would be equivalent to a log file, but bound to a Message. Of course there is already a logger, but in the end, I need to create (either after the Rest called is made, or when an error occurs) a file for this specific Message with the data.

I was wondering if there was some kind of "context" for the Message that I could call through any part of the chain, and where I could store stuff. I didn't found anything in the official documentation, but I'm not really sure about what to look for.

I've been thinking about putting it all in the Message itself, but:

  • It's an immutable object, so I would need to rebuild it each time I want to add something to its header (or the payload).
  • I wouldn't be able to retrieve any new data from the error handler in case of Exception, because it takes the original message.
  • I can't really add it to the payload object because some native transformers/service-activators are directly using it (and that would also mean rewriting a lot of code ...)

I've been also thinking to some king of "thread-bound" bean that would act as a context for each Message, but I see too many problem arising from this.

Maybe I'm wrong about some of these ideas. Anyway, I just need a way to keep data though multiple element of a Spring integration chain and also be able to access it in the error handler.

Questioner
Asoub
Viewed
75
Gary Russell 2019-07-04 00:08

Add a header, e.g. a map or list, and add to it in each stage.

The framework does something similar when message history is enabled.