【问题标题】:Using Spring Data Session bean in async task. Scope 'session' is not active for the current thread在异步任务中使用 Spring Data Session bean。范围“会话”对当前线程不活动
【发布时间】:2017-07-10 11:13:54
【问题描述】:

我有下一个流程要在我的 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.

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

【问题讨论】:

  • 您是否将@EnableAsync 添加到配置类中?
  • 我认为answer 会帮助你...
  • 是的,我添加了@EnableAsync
  • 为什么在长时间运行的任务中需要范围会话?不能只是一个单例吗?
  • 您使用的是哪个版本的 SDN?不再需要声明 Session bean。请使用 4.2.4 并参考此文档进行配置:docs.spring.io/spring-data/data-neo4j/docs/4.2.4.RELEASE 您应该会发现 @Async 请求工作正常。

标签: java spring spring-mvc spring-data spring-data-neo4j


【解决方案1】:

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

当您使用 @Async 注释方法时,执行将在另一个线程中进行,并且无法访问调用者(以及会话)的范围。

尝试在您的异步 bean 中注入 SessionFactory 以获取会话。

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

【讨论】:

    猜你喜欢
    • 2019-11-08
    • 2018-10-28
    • 2012-07-06
    • 2014-02-12
    • 2015-01-29
    • 1970-01-01
    • 2018-11-05
    • 1970-01-01
    • 2011-09-21
    相关资源
    最近更新 更多