Quarkus CDI 上下文与 Kotlin 协程

Dan*_*owe 5 quarkus

我正在尝试将一些 Hibernate / Hibernate Search 调用卸载到不同的线程,但我收到错误,表明 CDI 未在该线程中正确设置。

我查看了https://quarkus.io/guides/context-propagation上的指南,但没有提及 kotlin 协程。

有没有办法用协程来进行上下文传播?

我在用着

val entityReferences = withContext(Dispatchers.IO ) {
    //hibernate code here
}
Run Code Online (Sandbox Code Playgroud)
javax.enterprise.context.ContextNotActiveException
    at io.quarkus.arc.impl.ClientProxies.getDelegate(ClientProxies.java:40)
    at io.quarkus.hibernate.orm.runtime.RequestScopedSessionHolder_ClientProxy.arc$delegate(RequestScopedSessionHolder_ClientProxy.zig:42)
    at io.quarkus.hibernate.orm.runtime.RequestScopedSessionHolder_ClientProxy.getOrCreateSession(RequestScopedSessionHolder_ClientProxy.zig:102)
    at io.quarkus.hibernate.orm.runtime.session.TransactionScopedSession.acquireSession(TransactionScopedSession.java:104)
    at io.quarkus.hibernate.orm.runtime.session.TransactionScopedSession.createQuery(TransactionScopedSession.java:376)
    at io.quarkus.hibernate.orm.runtime.session.ForwardingSession.createQuery(ForwardingSession.java:188)
    at io.quarkus.hibernate.orm.runtime.session.ForwardingSession.createQuery(ForwardingSession.java:47)
    at org.hibernate.Session_5b93bee577ae2f8d76647de04cfab36afbf52958_Synthetic_ClientProxy.createQuery(Session_5b93bee577ae2f8d76647de04cfab36afbf52958_Synthetic_ClientProxy.zig:927)
Run Code Online (Sandbox Code Playgroud)

Dan*_*owe 2

我已成功通过创建自定义协程上下文将请求范围上下文附加到线程。

class RequestContextElement(private val controller: RequestContextController) : ThreadContextElement<Boolean>, AbstractCoroutineContextElement(Key) {
    companion object Key : CoroutineContext.Key<RequestContextElement>
    override fun updateThreadContext(context: CoroutineContext) = controller.activate()
    override fun restoreThreadContext(context: CoroutineContext, oldState: Boolean) = controller.deactivate()
}
Run Code Online (Sandbox Code Playgroud)

将 注入RequestContextController到正在创建协程的 bean 中。

@Inject
protected lateinit var requestContextController: RequestContextController
Run Code Online (Sandbox Code Playgroud)

然后将自定义上下文添加到协程上下文中

val entityReferences = withContext(Dispatchers.IO + RequestContextElement(requestContextController)) {
// Hibernate code
}
Run Code Online (Sandbox Code Playgroud)

我使用了以下资源

如有必要,第一个资源也可能有助于传播交易。