Home > Blockchain >  Java Spring - share data between several threads
Java Spring - share data between several threads

Time:06-19

I'm new to Java and Spring.

I have a Spring application, in a microservices architecture, I want to add a unique request id to each request to go along to all microservices. The way I thought of doing that, is when a request is enter a service, I look for a unique header, if it exists, I take the value of the header and store it in the context, if it doesn't exists, I generate a unique ID and store it in the context. On any outgoing network call, I take that value from the context and attache it to the request as a header.

That works great, until... Unfortunately, in one of our services, there is a lot of multi-threads usage using the @Async annotation. Because of this, I can't access the context and get the unique ID.

One option is to inject that ID into any Async method, however, that's ugly.

I'm new to Spring, but it sounds like a problem someone already solved in the past. I've tried to look for an answer but couldn't find.

Any idea?

CodePudding user response:

If you do this for tracing the requests through all the involved microservices, you can use Spring Cloud Sleuth.

All you need to do is add the maven/gradle dependency to all microservices and it will add tracing headers with a unique id to all outgoing calls or forward an existing one (if the microservice was called with it).

CodePudding user response:

As suggested in above answer - Use Sleuth for getting trace ID and Span ID to determine various threads across multiple microservices. You can also configure exisitng logging service such as logback, log4j2, sl4j to push logs via sleuth.

Additionaly, you can configure zipkin for analysing any operation from this trace and span id. Zipkin will act as centralised manager for disctributed tracing.

  • Related