gpt4 book ai didi

java - 在新线程中调用连接点时 Spring Aspect 失败

转载 作者:搜寻专家 更新时间:2023-10-31 20:30:30 25 4
gpt4 key购买 nike

我正在使用带有 Around 方面的 Spring 3.0.5。

@Around 方面工作得很好。 AOP 表达式以一堆 bean 的接口(interface)为目标。

方面在调用前后执行一些逻辑:

 @Around(...)
public Object monitor(ProceedingJoinPoint pjp) throws Throwable {
// some code
Obj o = pjp.proceed();
// some code
}

没什么大不了的。

现在,我正在尝试创建另一个方面,如果被拦截的方法花费的时间太长,它会引发异常。

private static ExecutorService executor = Executors.newCachedThreadPool();

@Around(...)
public Object monitor(ProceedingJoinPoint pjp) throws Throwable {

Object obj = null;

Callable<Object> task = new Callable<Object>() {
public Object call() {
return pjp.proceed();
}
};
Future<Object> future = executor.submit(task);
try {
obj = future.get(timeout, TimeUnit.MILLISECONDS);
} catch (TimeoutException ex) {
...
} catch (InterruptedException e) {
// we ignore this one...
} catch (ExecutionException e) {
throw e.getCause(); // rethrow any exception raised by the invoked method
} finally {
future.cancel(true); // may or may not desire this
}

return obj;
}

当我执行仅应用此方面的代码时,出现以下异常:

java.lang.RuntimeException: java.lang.IllegalStateException: No MethodInvocation found: Check that an AOP invocation is in progress, and that the ExposeInvocationInterceptor is in the interceptor chain.

来自Spring documentation我读:

“类 ExposeInvocationInterceptor

将当前 MethodInvocation 公开为线程本地对象的拦截器。”

所以看起来目标丢失了,因为我基本上启动了一个新线程,而新线程无法访问本地线程。有没有办法解决这个问题或更好的方法?

谢谢

最佳答案

解决方案非常简单。检查方法需要多长时间的方面必须是方面“链”中的最后一个。我在切面上使用了 @Order 注释,使其成为最后一个执行的切面。

成功了。

如果切面不是最后执行的,则新线程无法访问包含 ExposeInvocationInterceptor 类的 ThreadLocal 变量。

关于java - 在新线程中调用连接点时 Spring Aspect 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7147031/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com