Last active
December 19, 2018 09:42
-
-
Save JorgenRingen/b84b6c99ab16c1f7d4ea7e19ec49857b to your computer and use it in GitHub Desktop.
MdcTaskDecoratorExample
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package no.vegvesen.kjoretoy.registrering.forhandler.web.config; | |
import java.util.concurrent.Executor; | |
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler; | |
import org.springframework.context.annotation.Configuration; | |
import org.springframework.context.annotation.Import; | |
import org.springframework.core.task.SimpleAsyncTaskExecutor; | |
import org.springframework.scheduling.annotation.AsyncConfigurer; | |
import org.springframework.scheduling.annotation.EnableAsync; | |
import no.vegvesen.kjoretoy.registrering.forhandler.service.config.AkrForhandlerServiceSpringConfig; | |
import no.vegvesen.kjoretoy.registrering.logging.mdc.MdcTaskDecorator; | |
@EnableAsync | |
@Import({ | |
ServiceSpringConfig.class | |
}) | |
@Configuration | |
public class ServiceSpringConfig implements AsyncConfigurer { | |
@Override | |
public Executor getAsyncExecutor() { | |
SimpleAsyncTaskExecutor simpleAsyncTaskExecutor = new SimpleAsyncTaskExecutor(); | |
simpleAsyncTaskExecutor.setTaskDecorator(new MdcTaskDecorator()); | |
return simpleAsyncTaskExecutor; | |
} | |
@Override | |
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() { | |
// Return null to keep default implementation | |
return null; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package no.vegvesen.kjoretoy.registrering.logging.mdc; | |
import java.util.Map; | |
import org.slf4j.MDC; | |
import org.springframework.core.task.TaskDecorator; | |
/** | |
* Propagerer MDC-contexten til asynkrone tråder startet av {@code @Async} slik | |
* at svvguid, trace-id, bruker-id osv blir tilgjengelig. | |
* <p> | |
* Må legges til på executoren som starter asynkrone jobber: | |
* {@code simpleAsyncTaskExecutor.setTaskDecorator(new MdcTaskDecorator());} | |
*/ | |
public class MdcTaskDecorator implements TaskDecorator { | |
@Override | |
public Runnable decorate(Runnable runnable) { | |
Map<String, String> contextMap = MDC.getCopyOfContextMap(); | |
return () -> { | |
try { | |
if (contextMap != null) { | |
MDC.setContextMap(contextMap); | |
} | |
runnable.run(); | |
} finally { | |
MDC.clear(); | |
} | |
}; | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment