java.lang.IllegalStateException:在异步方面使用 RequestContextHolder.currentRequestAttributes() 时未找到线程绑定请求 [英] java.lang.IllegalStateException: No thread-bound request found when using RequestContextHolder.currentRequestAttributes() in async aspect

查看:58
本文介绍了java.lang.IllegalStateException:在异步方面使用 RequestContextHolder.currentRequestAttributes() 时未找到线程绑定请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下方面,出于某些原因,您可以看到 此处,必须在方面方法上使用 @EnableAsync@Async ,如下所示:

I have this below aspect and for some reasons that you can see here, had to use @EnableAsync and @Async over aspect method as you can see below:

@Aspect
@Component
@EnableAsync
public class ApiCallLogAspect {

    @Async
    @AfterReturning(value = ("within(com.example..*.web.rest.api..*)"), returning = "returnValue")
    public void endpointAfterReturning(JoinPoint p, Object returnValue) throws InterruptedException {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
        System.out.println(request.getHeader("authorization"));
    }

}

现在,我得到这个异常:

Now, i get this exception:

java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.
    at org.springframework.web.context.request.RequestContextHolder.currentRequestAttributes(RequestContextHolder.java:131) ~[spring-web-5.2.7.RELEASE.jar:5.2.7.RELEASE]
    at com.example.web.rest.api.ApiCallLogAspect.endpointAfterReturning(ApiCallLogAspect.java:40) ~[classes/:na]
    at com.example.web.rest.api.ApiCallLogAspect$$FastClassBySpringCGLIB$$f034ee12.invoke(<generated>) ~[classes/:na]
    at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218) ~[spring-core-5.2.7.RELEASE.jar:5.2.7.RELEASE]
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:771) ~[spring-aop-5.2.7.RELEASE.jar:5.2.7.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163) ~[spring-aop-5.2.7.RELEASE.jar:5.2.7.RELEASE]
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:749) ~[spring-aop-5.2.7.RELEASE.jar:5.2.7.RELEASE]
    at org.springframework.aop.interceptor.AsyncExecutionInterceptor.lambda$invoke$0(AsyncExecutionInterceptor.java:115) ~[spring-aop-5.2.7.RELEASE.jar:5.2.7.RELEASE]
    at java.util.concurrent.FutureTask.run(FutureTask.java:266) ~[na:1.8.0_162]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) ~[na:1.8.0_162]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) ~[na:1.8.0_162]
    at java.lang.Thread.run(Thread.java:748) ~[na:1.8.0_162]

我该如何解决这个问题?有没有办法从

How can i solve this? is there a way to get request headers from

推荐答案

我通过下面的@M.Deinum 评论解决了这个问题:

I solved the problem by these changes below with @M.Deinum comments:

public class ThreadContextHolder {
    private ThreadContextHolder() {
    }

    private static final ThreadLocal<Map<String, Object>> ctx = new ThreadLocal<>();

    public static Map<String, Object> getContext() {
        return ctx.get();
    }

    public static void setContext(Map<String, Object> attrs) {
        ctx.set(attrs);
    }

    public static void removeContext() {
        ctx.remove();
    }
}

然后将taskExecutor注入ApiCallLogAspect类:

@Bean
public Executor taskExecutor() {
    ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();

    executor.setTaskDecorator(
            runnable -> {
                HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();

                Map<String, Object> headers = new HashMap<>();
                for (String header : Collections.list(request.getHeaderNames())) {
                    headers.put(header, request.getHeader(header));
                }

                return () -> {
                    try {
                        ThreadContextHolder.setContext(headers);
                        runnable.run();
                    } finally {
                        ThreadContextHolder.removeContext();
                    }
                };
            });

    executor.initialize();
    return executor;
}

然后将 endpointAfterReturning 方法更改为它:

and then change endpointAfterReturning method to it:

@Async
@AfterReturning(value = ("within(com.example..*.web.rest.api..*)"), returning = "returnValue")
public void endpointAfterReturning(JoinPoint p, Object returnValue) throws InterruptedException {
    Map<String, String> headers = new HashMap<>();
    ThreadContextHolder.getContext().forEach((s, o) -> headers.put(s, o.toString()));
    System.out.println(headers.get("authorization"));
}

现在,一切正常.如果此解决方案有问题,请通知我.

Now, everything works fine. If this solution has a problem please notify to me.

这篇关于java.lang.IllegalStateException:在异步方面使用 RequestContextHolder.currentRequestAttributes() 时未找到线程绑定请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆