在Threads中访问作用域代理bean [英] Accessing scoped proxy beans within Threads of

查看:99
本文介绍了在Threads中访问作用域代理bean的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个在tomcat中运行的Web应用程序,我正在使用ThreadPool(Java 5 ExecutorService)并行运行IO密集型操作以提高性能。我想让每个池化线程中使用的一些bean都在请求范围内,但ThreadPool中的Threads无法访问spring上下文并获得代理失败。关于如何为ThreadPool中的线程提供弹簧上下文以解决代理失败的任何想法?

I have a web application running in tomcat where I'm using a ThreadPool (Java 5 ExecutorService) to run IO intensive operations in parallel to improve performance. I would like to have some of the beans used within each pooled thread be in the request scope, but the Threads in the ThreadPool do not have access to the spring context and get a proxy failure. Any ideas on how to make the spring context available to the threads in the ThreadPool to resolve the proxy failures?

我猜必须有办法注册/取消注册ThreadPool中的每个线程都有弹簧用于每个任务,但是没有运气找到如何做到这一点。

I'm guessing there must be a way to register/unregister each thread in the ThreadPool with spring for each task, but haven't had any luck finding how to do this.

谢谢!

推荐答案

我正在使用以下超类来完成需要访问请求范围的任务。基本上你可以扩展它并在onRun()方法中实现你的逻辑。

I am using the following super class for my tasks that need to have access to request scope. Basically you can just extend it and implement your logic in onRun() method.

import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

/**
 * @author Eugene Kuleshov
 */
public abstract class RequestAwareRunnable implements Runnable {
  private final RequestAttributes requestAttributes;
  private Thread thread;

  public RequestAwareRunnable() {
    this.requestAttributes = RequestContextHolder.getRequestAttributes();
    this.thread = Thread.currentThread();
  }

  public void run() {
    try {
      RequestContextHolder.setRequestAttributes(requestAttributes);
      onRun();
    } finally {
      if (Thread.currentThread() != thread) {
        RequestContextHolder.resetRequestAttributes();
      }
      thread = null;
    }
  }

  protected abstract void onRun();
}

这篇关于在Threads中访问作用域代理bean的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆