【问题标题】:Configure default Kotlin coroutine context in Spring MVC在 Spring MVC 中配置默认​​ Kotlin 协程上下文
【发布时间】:2021-07-19 09:08:07
【问题描述】:

我需要为 Spring MVC 中的所有请求配置默认协程上下文。例如 MDCContext(与 this 类似的问题,但对于 MVC 而不是 WebFlux)。

我尝试过的

  1. 挂钩 Spring - 协程代码为 here 但无法更改默认行为(需要更改 InvocableHandlerMethod.doInvoke 实现)
  2. 使用 AOP - AOP 和协程不使用 play well together

有什么想法吗?

【问题讨论】:

  • 其实第1点是不对的,可以使用WebMvcRegistrations注册自定义的RequestMappingHandlerAdapter

标签: spring spring-mvc kotlin-coroutines


【解决方案1】:

这似乎有效:

@Configuration
class ContextConfig: WebMvcRegistrations {

    override fun getRequestMappingHandlerAdapter(): RequestMappingHandlerAdapter {
        return object: RequestMappingHandlerAdapter() {
            override fun createInvocableHandlerMethod(handlerMethod: HandlerMethod): ServletInvocableHandlerMethod {
                return object : ServletInvocableHandlerMethod(handlerMethod) {
                    override fun doInvoke(vararg args: Any?): Any? {
                        val method = bridgedMethod
                        ReflectionUtils.makeAccessible(method)
                        if (KotlinDetector.isSuspendingFunction(method)) {
                            // Exception handling skipped for brevity, copy it from super.doInvoke()
                            return invokeSuspendingFunctionX(method, bean, *args)
                        }
                        return super.doInvoke(*args)
                    }

                    /**
                     * Copied from CoroutinesUtils in order to be able to set CoroutineContext
                     */
                    @Suppress("UNCHECKED_CAST")
                    private fun invokeSuspendingFunctionX(method: Method, target: Any, vararg args: Any?): Publisher<*> {
                        val function = method.kotlinFunction!!
                        val mono = mono(YOUR_CONTEXT_HERE) {
                            function.callSuspend(target, *args.sliceArray(0..(args.size-2))).let { if (it == Unit) null else it }
                        }.onErrorMap(InvocationTargetException::class.java) { it.targetException }
                        return if (function.returnType.classifier == Flow::class) {
                            mono.flatMapMany { (it as Flow<Any>).asFlux() }
                        }
                        else {
                            mono
                        }
                    }
                }
            }
        }
    }
}

【讨论】:

    猜你喜欢
    • 2019-06-22
    • 1970-01-01
    • 1970-01-01
    • 2016-03-21
    • 1970-01-01
    • 2020-02-18
    • 2012-04-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多