gpt4 book ai didi

java - Spring webflux : keeping an EntityManager open during the whole process of a reactive request handling

转载 作者:行者123 更新时间:2023-12-02 09:34:58 26 4
gpt4 key购买 nike

在标准同步 Spring (WebMVC) 世界中,有 OpenEntityManagerInViewFilterOpenEntityManagerInViewInterceptor 在整个处理过程中保持 JPA EntityManager 打开。请求并允许避免烦人的 LazyInitializationException(“无 session ”)。

OpenEntityManagerInViewInterceptor 对于基于异步 servlet API 的应用程序也以类似的方式工作。

但是在 Webflux 应用程序中如何处理这个问题呢?假设我有一个 Webflux Controller ,它可以执行类似的操作

service.getOneReactively(...).flatMapMany(one -> obtainAFlux(one))

其中 service.getOneReactively() 在数据库中查找域对象,并且 obtainAFlux() 访问该域对象上的惰性集合,从而导致其加载。这两个调用都将在某个线程池上执行,可能在不同的线程上执行,因此 Hibernate 的 Session 绑定(bind)到第一个线程(其中具体化了域对象)将无法在第二个线程(其中集合已加载)。

这会导致LazyInitializationException

遇到这样的问题怎么解决呢?到目前为止,我唯一能发明的就是将这两个调用打包到一个方法中,并在一个 react ​​式调用的事务中调用它。

最佳答案

Hibernate 不是响应式的,它使用 JDBC,这是一个阻塞数据库驱动程序,并且它又使用 threadlocal 来存储在 Webflux 中无法使用的 session 信息。

如果您希望执行阻塞数据库调用,则必须使用 Mono.fromCallable 并将调用分配给它自己的调度程序,以便它获得自己的专用线程。您可以在文档 https://projectreactor.io/docs/core/release/reference/#faq.wrap-blocking 中阅读更多相关信息。 hibernate 本身无法返回 Flux。

你的代码应该是这样的

Flux<Objects> myObjects = Mono.fromCallable(() -> {

// make all your calls to the database here
// build then your flux or whatever you want

return Flux.fromIterable(listOfObjects);
}).subscribeOn(Schedulers.elastic()); // Makes sure this is run in its own thread

关于java - Spring webflux : keeping an EntityManager open during the whole process of a reactive request handling,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57597313/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com