Catch Return 个拦截器的值

Catch Return Value of An Interceptor

我想检索此拦截器的 return 值:

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???

所以我的问题是如何检索 return 值(在我的 FutureDelegator 示例中)???

你不会的。 EJB 和 Tijms 建议的模型中的异步调用是“即发即弃”:您调用它们并让它们完成它们的工作。最终,你可以让异步方法在结果为“return”时触发一些事件,观察这个事件给用户一些响应(websockets,也许?)。

理想情况下,异步方法应该为 void 并执行一些回调提升。

请注意,CDI 2.0 事件模型具有 fireAsync 方法,应该使用该方法而不是您自己的实现,因为它已经具有适当的上下文并且可以通过事务标记和自定义选项(使用时NotificationOptions 方法签名).