使用背景:今天在spring-cloud项目中,使用多线程异步调用微服务出现的错误 
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.

 

具体场景:

为防止响应时间过长,异步处理请求,但是在处理中有FileClient调用

 

解决思路:

//异步调用,设置子线程共享
ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
RequestContextHolder.setRequestAttributes(servletRequestAttributes,true);//设置子线程共享
//此处你的业务逻辑
});

 

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐