问题描述
我正在Ktor中建立一个微服务.当我们在应用程序模块中工作时,Ktor提供对包含授权数据的call
对象的访问.
I'm building a microservice in Ktor. While we are working within the application module, Ktor provides access to the call
object which contains authorization data.
我的问题是我需要从服务级别的类访问call
对象.在Spring中,您可以通过访问SecurityContext
来做到这一点,而SecurityContext
可以通过ThreadLocal
在全球范围内使用.协程驱动的Ktor没有这种选择.
My problem is that I need to access the call
object from a service-level class. In Spring, you would do this by accessing the SecurityContext
which is globally available via a ThreadLocal
. Ktor, being coroutine-driven, does not have that option.
我真的需要通过服务层方法传递call
对象,还是在Ktor中有一种方法可以让您从任何地方访问某种调用上下文"对象?
Do I really need to pass down the call
object through my service layer methods, or is there a way in Ktor to have some sort of "call context" object that you can access from anywhere?
推荐答案
我认为目前没有内置的官方机会.
I think there is no build-in official opportunity at the moment.
我写了一个实现该行为的Ktor功能.答案是用几句话来形容它很复杂.
I have written a Ktor-Feature, that implements that behaviour.The answer is to complicated to describe it in a few words.
如果有兴趣,请查看代码+示例.还提供了安装指南.
Check out the code + samples, if you are interested. Also an install guide is provided.
=> https://github.com/MaaxGr/ktor-globalcalldata
直接或从路由间接调用暂停函数test():
Call suspending function test() directly or indirectly from a route:
routing {
get("/test") {
test()
call.respond("OK")
}
}
通过callData().call
suspend fun test() {
val url = callData().call.request.uri
println(url) // prints "/test"
}
该库还允许添加可以绑定到当前协程/调用的自定义属性.
The library also allows to add custom properties that can be bound to the current coroutine/call.
这篇关于如何使请求绑定的数据在Ktor中全局可用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!