Advertisement
Guest User

Untitled

a guest
Sep 18th, 2019
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.88 KB | None | 0 0
  1. class CustomNowAsync {
  2. companion object : KLogging() {
  3. fun <T> globalScopeAsync(block: () -> T): Deferred<T> =
  4. GlobalScope.async(
  5. context = CustomNowAsyncContext(),
  6. start = CoroutineStart.DEFAULT
  7. )
  8. { block.invoke() }
  9.  
  10. fun globalScopeLaunch(block: () -> Unit): Job =
  11. GlobalScope.launch(
  12. context = CustomNowAsyncContext(),
  13. start = CoroutineStart.DEFAULT
  14. )
  15. { block.invoke() }
  16.  
  17. private fun getServletRequestAttributes(): ServletRequestAttributes? =
  18. RequestContextHolder.getRequestAttributes()
  19. ?.let {
  20. if (ServletRequestAttributes::class.java.isAssignableFrom(it.javaClass)) {
  21. it as ServletRequestAttributes
  22. } else {
  23. null
  24. }
  25. }
  26. }
  27.  
  28. class CustomNowAsyncContext(
  29. private val contextMap: Map<String, String> = MDC.getCopyOfContextMap() ?: emptyMap(),
  30. private val servletRequestAttributes: ServletRequestAttributes? = getServletRequestAttributes(),
  31. ) : ThreadContextElement<Map<String, String>>, AbstractCoroutineContextElement(Key) {
  32.  
  33. companion object Key : CoroutineContext.Key<CustomNowAsyncContext>
  34.  
  35. override fun updateThreadContext(context: CoroutineContext): Map<String, String> {
  36. val oldState = MDC.getCopyOfContextMap() ?: emptyMap()
  37.  
  38. MDC.setContextMap(contextMap)
  39.  
  40. servletRequestAttributes?.let {
  41. RequestContextHolder.setRequestAttributes(it)
  42. }
  43. return oldState
  44. }
  45.  
  46. override fun restoreThreadContext(context: CoroutineContext, oldState: Map<String, String>) {
  47. RequestContextHolder.setRequestAttributes(null)
  48. MDC.setContextMap(oldState)
  49. }
  50. }
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement