1

I have a Kafka consumer implemented as :

@KafkaListener(topics="...", group-id="....")
public void doProcessing(@Payload String data, @Headers Map<String, Object> headers)
{
//read one of the headers and get a unique id pertaining for thread
//set that header value in MDC
String messageUniqueIdentifier=headers.get("myRequestIdentifierKey");
MDC.put("myRequestIdentifierKey",messageUniqueIdentifier)
log.info("logging just to see if the unique identifier comes in the logs or not);
//do some processing
}

Is this a safe approach? Is it always gauranteed that the same thread will service one message in the consumer?

1 Answers1

3

It's not clear what you are asking. If you have concurrency there will be more than one thread but each message will be processed on one thread (as long as your listener doesn't hand off to another thread).

So, as long as you set the MDC in the listener each time and don't hand off to another thread; it will work.

If you have only one thread, the same thread will be used for every message (unless the container is stopped and restarted, in which case it will get a new thread).

Gary Russell
  • 166,535
  • 14
  • 146
  • 179