本文介绍了与RequestScope链接的本地线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用Capt的VRaptor构建的Web服务(焊接2.1.2.Final)。我需要并行处理服务器所做的一些处理(工业警报的统计分析)。我正在使用ExecutorService和Callable实例进行此操作,很遗憾,我的线程中需要一个请求范围依赖项。由于这种依赖性,我遇到了这个错误:

  WELD-001303:作用域类型javax.enterprise.context没有活动上下文.RequestScoped 

是否有一种方法可以将线程链接到使用CDI创建的请求? / p>

*我知道我不应该在服务器中打开线程,但这是当前最可行的选择

解决方案

将其作为可调用对象的构造函数参数传递。

 公共类YourTask实现Callable< ; String> {

私人的YourData数据;

public YourTask(YourData data){
this.data = data;
}

@Override
public String call(){
//只使用数据。
}

}
  @注入
私有YourRequestScopedBean bean;

public void commit(){
YourTask task = new YourTask(bean.getData());
// ...
}

注意:请勿传递bean本身,因为它基本上是一个,其实例在其他线程中不存在。



另请参见:










无关问题是,即使通过正确编程的 ExecutorService 完成操作,也无法手动管理Java EE容器中的线程。它表明您不知道Java EE的EJB调度和计时器API的可能性。您可能会发现此答案中的示例很有用:


I have a web service built with VRaptor that uses CDI (weld 2.1.2.Final). I need to parallelize some of the processing made by the server (statistical analysis of industrial alarms). I'm doing that using a ExecutorService and Callable instances, unfortunately I need one Request Scoped dependence inside my Threads. Because of that dependence I'm facing this error:

WELD-001303: No active contexts for scope type javax.enterprise.context.RequestScoped

Is there a way to link the Threads to the Request where they were created using CDI?

*I know that I shouldn't be opening threads in the server, but this is the currently most viable option

解决方案

Pass it as constructor argument of the callable.

public class YourTask implements Callable<String> {

    private YourData data;

    public YourTask(YourData data) {
        this.data = data;
    }

    @Override
    public String call() {
        // Just use data.
    }

}
@Inject
private YourRequestScopedBean bean;

public void submit() {
    YourTask task = new YourTask(bean.getData());
    // ...
}

Note: do not pass the bean itself as it's basically a proxy whose instance doesn't exist in other thread.

See also:


Unrelated to the concrete problem, manually managing threads in a Java EE container, even though when done via a properly programmed ExecutorService, is frowned upon. It indicates you aren't aware of possibilities of Java EE's EJB scheduling and timer APIs. You may find the examples in this answer useful: Is it safe to start a new thread in a JSF managed bean?

这篇关于与RequestScope链接的本地线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 18:36