Spring Webflux:CoRouter CoRouterFunctionDsl(Coroutine)-context not applied to onError

dba5bblo  于 5个月前  发布在  Spring
关注(0)|答案(1)|浏览(48)

我正在使用spring Boot 3.2和spring框架的底层版本6.1.1运行带有Kotlin协程的web flux。
我使用micrometer进行跟踪。对于spring的coRouter,我遵循这里的示例:https://github.com/spring-projects/spring-framework/issues/27010来设置corouter中的上下文,因此所有后续调用都可以访问MdcContext
但是如果我定义了一个onError函数,上下文并不应用于该函数。是否有特殊的方法来实现这一点,或者我必须手动将上下文作为函数参数发送?
范例:

@Bean
fun demoRoutes() = coRouter {
    "/rest".nest {
        "v1".nest {
            "/demo".nest {
                context { observationRegistry.asContextElement() }
                GET("", demoHandler::demoCall)
            }
        }
    }
    onError<RuntimeException> { throwable, serverRequest ->
        errorHandler.handleError(throwable, serverRequest)
    }
}

字符串
另一个补充问题:有没有什么方法可以让context适用于所有情况?只有在最后一个nest函数中设置了它才适用。如果我将它定义为父函数或直接在coRouter中定义,它就不起作用了:

@Bean
fun demoRoutes() = coRouter {
    context { observationRegistry.asContextElement() }
    "/rest".nest {
        "v1".nest {
            "/demo".nest {
                GET("", demoHandler::demoCall)
            }
        }
    }
    onError<RuntimeException> { throwable, serverRequest ->
        errorHandler.handleError(throwable, serverRequest)
    }
}


如果这样使用,则在对demoHandler::demoCall的调用中会丢失上下文。

5cnsuln7

5cnsuln71#

据我所知,错误处理的行为似乎还可以,但是当将嵌套路由器和CoroutineContext结合使用时,确实有一个令人惊讶的行为,这应该由https://github.com/spring-projects/spring-framework/issues/31831修复。

相关问题