我想获取此拦截器的返回值:
https://arjan-tijms.omnifaces.org/2012/01/cdi-based-asynchronous-alternative.html
@Interceptor
@Asynchronous
@Priority(PLATFORM_BEFORE)
public class AsynchronousInterceptor implements Serializable {
private static final long serialVersionUID = 1L;
@Resource
private ManagedExecutorService managedExecutorService;
private static final ThreadLocal<Boolean> asyncInvocation = new ThreadLocal<Boolean>();
@AroundInvoke
public synchronized Object submitAsync(InvocationContext ctx) throws Exception {
if (TRUE.equals(asyncInvocation.get())) {
return ctx.proceed();
}
return new FutureDelegator(managedExecutorService.submit( ()-> {
try {
asyncInvocation.set(TRUE);
return ctx.proceed();
} finally {
asyncInvocation.remove();
}
}));
}
}
这是我的CdiBean,它通过让数据异步加载而从AsynchronousInterceptor中获利。
public class SomeCDI {
@Asynchronous
public void loadDataAsync() {....}
}
这是我稍后在代码中使用cdi bean的方式:
@Inject
SomeCDI dataLoader;
dataLoader.loadDataAsync(); // the loading starts async but I never find out when is the Future class done???
所以我的问题是如何获取返回值(在我的示例中为FutureDelegator)?
答案 0 :(得分:1)
您不会。在EJB和Tijms建议的模型中,对EJB的异步调用是“一劳永逸”的:您调用它们并让它们完成其工作。最终,您可以使async方法在结束时触发某个事件以“返回”结果,并观察该事件以向用户提供一些响应(也许是websockets?)。
理想情况下,异步方法应该为空,并进行一些回调。
请注意,CDI 2.0事件模型具有fireAsync方法,应使用该方法代替您自己的实现,因为它已经具有适当的上下文,并且可以通过事务标记和自定义选项来充实(使用NotificationOptions方法时)签名)。