繁体   English   中英

在异步任务中使用Spring Data Session bean。 作用域“会话”对于当前线程无效

[英]Using Spring Data Session bean in async task. Scope 'session' is not active for the current thread

我的下一个流程要在我的Spring MVC Web应用程序中实现:

  • 用户在页面上插入一些值,即对服务器进行POST
  • 基于此值,控制器将启动一个长时间运行的后台任务,即非常繁重(大约一小时左右),因此绝对需要异步。
  • 在此任务期间,需要对数据库进行读/写操作(在我的情况下是Neo4j)

我是如何做到的:

  1. 我们在作用域“会话”中有bean:
@Bean
@Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS)
public Session getSession() throws Exception {
    return super.getSession();
}
  1. 在我的控制器中,我有一些数据库存储库:
@Autowired
SomeDBRepo repo;
  1. 我有一个方法,由@Async注释
@Async 
doSomeAsync() {
   repo.findAll();
}

我收到此错误:

Error creating bean with name 'scopedTarget.getSession': Scope 'session' is not active for the current thread; consider defining a scoped proxy for this bean if you intend to refer to it from a singleton; nested exception is java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.

我已经阅读了一些有关此问题的文章,但没有任何帮助。 这个问题怎么解决?

Spring中的会话和请求范围是线程绑定的。

当您使用@Async注释方法时,执行将在另一个线程中进行,并且无法访问调用方的作用域(并因此无法访问会话)。

尝试将SessionFactory注入异步bean中以获取Session。

顺便说一句,您确定您确实需要一个会话范围吗? 这会将OGM会话存储在Web会话中,这可能导致负载下的内存问题,因为该会话充当数据库的一级缓存。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM