当方法返回CompletionStage时,我遇到了一个问题,即我的过滤器运行了两次.从RequestMapping(here)上的文档中,它是受支持的返回值.
A CompletionStage (implemented by CompletableFuture for example) which the application uses to produce a return value in a separate thread of its own choosing,as an alternative to returning a Callable.
由于项目非常复杂,并且有很多并发代码,因此我创建了一个新的简单的spring-boot项目.这是(唯一的)控制器:
@Controller
public class BaseController {
@RequestMapping("/hello")
@ResponseBody
public CompletionStageCompletableFuture.supplyAsync(() -> "Hello World");
}
}
还有一个过滤器:
@WebFilter
@Component
public class GenericLoggingFilter extends GenericFilterBean {
@Override
public void doFilter(ServletRequest request,ServletResponse response,FilterChain chain) throws IOException,ServletException {
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
System.out.println(httpServletRequest.getMethod() + " " +
httpServletRequest.getRequestURI());
chain.doFilter(request,response);
}
}
当我打电话curl http:// localhost:8080 / hello时,它会在控制台上打印两次GET / hello.当我更改控制器方法以返回String时:
@RequestMapping("/hello")
@ResponseBody
public String world() {
return "Hello World";
}
它只打印一次.即使我将其更改为Callable也会出现此行为,Callable没有真正的并发意义(当然,spring本身可能会将此视为异步请求).
因此,如果spring再次运行整个Web堆栈以获得请求上下文,那么即使这样也没有意义,因为以下内容:
@RequestMapping("/hello")
@ResponseBody
public CompletionStageCompletableFuture.supplyAsync(() -> {
System.out.println(RequestContextHolder.currentRequestAttributes());
return "Hello World";
});
}
抛出异常:IllegalStateException:找不到线程绑定请求…
令人惊讶的是,以下工作:
@RequestMapping("/hello")
@ResponseBody
public Callable
所以,我不确定相当多的事情.
>似乎Callable和CompletionStage在执行哪个线程的上下文中被区别对待.
>如果是这种情况,为什么我的过滤器在每种情况下运行两次?如果过滤器的工作是设置某个特定于请求的上下文,那么如果无法访问CompletionStage,则再次运行它是没有意义的.
>为什么过滤器运行两次到底是哪种方式?