Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class CustomNowAsync {
- companion object : KLogging() {
- fun <T> globalScopeAsync(block: () -> T): Deferred<T> =
- GlobalScope.async(
- context = CustomNowAsyncContext(),
- start = CoroutineStart.DEFAULT
- )
- { block.invoke() }
- fun globalScopeLaunch(block: () -> Unit): Job =
- GlobalScope.launch(
- context = CustomNowAsyncContext(),
- start = CoroutineStart.DEFAULT
- )
- { block.invoke() }
- private fun getServletRequestAttributes(): ServletRequestAttributes? =
- RequestContextHolder.getRequestAttributes()
- ?.let {
- if (ServletRequestAttributes::class.java.isAssignableFrom(it.javaClass)) {
- it as ServletRequestAttributes
- } else {
- null
- }
- }
- }
- class CustomNowAsyncContext(
- private val contextMap: Map<String, String> = MDC.getCopyOfContextMap() ?: emptyMap(),
- private val servletRequestAttributes: ServletRequestAttributes? = getServletRequestAttributes(),
- ) : ThreadContextElement<Map<String, String>>, AbstractCoroutineContextElement(Key) {
- companion object Key : CoroutineContext.Key<CustomNowAsyncContext>
- override fun updateThreadContext(context: CoroutineContext): Map<String, String> {
- val oldState = MDC.getCopyOfContextMap() ?: emptyMap()
- MDC.setContextMap(contextMap)
- servletRequestAttributes?.let {
- RequestContextHolder.setRequestAttributes(it)
- }
- return oldState
- }
- override fun restoreThreadContext(context: CoroutineContext, oldState: Map<String, String>) {
- RequestContextHolder.setRequestAttributes(null)
- MDC.setContextMap(oldState)
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement