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

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

问题描述

我有一个在 tomcat 中运行的 Web 应用程序,我在其中使用 ThreadPool (Java 5 ExecutorService) 并行运行 IO 密集型操作以提高性能.我希望每个池线程中使用的一些 bean 都在请求范围内,但是 ThreadPool 中的线程无权访问 spring 上下文并导致代理失败.关于如何使 ThreadPool 中的线程可以使用 spring 上下文以解决代理故障的任何想法?

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?

我猜必须有一种方法可以使用 spring 为每个任务注册/取消注册 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天全站免登陆