有些业务场景下,可能会心愿应用线程池异步解决申请,或者开启一个新线程做一些运算,在这些异步环境下,又心愿能从源申请的request对象中拿到一些头信息或者申请参数。

罕用到的一种做法,是在开启异步工作前,从主线程中拿到request的 ServletRequestAttributes 对象,并避免到子线程中,例如:

    @GetMapping("asyncRequest")    @SneakyThrows    public void test(){        // 主线程request传递        final ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();        new Thread(() -> {            RequestContextHolder.setRequestAttributes(attributes);            for (int i = 0; i < 10; i++) {                System.out.println(((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getRequestURI());                try {                    Thread.sleep(1000);                } catch (InterruptedException e) {                    throw new RuntimeException(e);                }            }        }).start();        Thread.sleep(5000);    }

这段代码比较简单,从主线程拿到申请属性,设置到子线程中去,子线程开启后什么事儿不干,分心打印申请uri,一秒一次,打印十次,主线程5秒后完结并返回。

失常来讲,成果也应该很简略,10次申请门路的打印罢了。然而实际效果略微有点意外:

能够看到,打印了6次之后,前面突然变成null了。why?

因为我用的spring-boot的内嵌tomcat容器,玄机就在 CoyoteAdapter 这个类里。关上源码,在 service() 办法的 finally 最上面有这么一段:

            req.getRequestProcessor().setWorkerThreadName(null);            req.clearRequestThread();            // Recycle the wrapper request and response            if (!async) {                updateWrapperErrorCount(request, response);                request.recycle();                response.recycle();            }

咱们的申请没有开启异步,所以会走上面的recycle办法,毋庸置疑,这是用来销毁并回收request对象的,而后面通过 RequestContextHolder.setRequestAttributes(attributes) 设置到以后线程的requestAttributes对象,察看源码可知,也只是把requestAttributes放到子线程的ThreadLocal里而已。当源对象被销毁,这里的援用只会指向一个空壳,没有报npe,然而拿不到任何数据了。

所以,如果要从主线程传递request到子线程,要么花大老本clone一个,要么还是用什么取出来什么,手动传递过来吧。