(1)分析
【1】在某些场景下我们希望在Service业务逻辑层获取到当前的HttpServletRequest对象,一个简单直接的处理办法是HttpServletRequest对象通过方法参数传递到下一层,但是这种办法并不灵活,我们需要一种更为通用和灵活的方式。
【2】对于这种需要在整个线程内使用的对象,我们很容易想到借助于ThreadLocal对象,是的我们可以使用该组件。然后再借助于RequestListener监听器,通过实现该接口在请求进入时将当前的HttpServletRequest添加到特定的ThreadLocal容器中,然后再后面的业务层中就可以直接在当前特定的ThreadLocal容器中获取HttpServletRequest对象。
【3】上面所描述的功能我们可以通过以下几种方式去实现 利用ServletRequestListener实现 利用Filter实现 利用拦截器实现
【4】对于上面所描述的功能,需要特别注意的一点是只能在一个线程中去实现该功能。在很多的场景下,在接收到请求之后,我们会通过异步子线程的方式去分担任务处理以此提高处理效率。那么如果在异步子线程中去获取ThreadLocal中的对象又会存在问题了,需要我们特别注意。
(2)常见的实现方式
下面几种实现原理都是一样的,使用一个ThreadLocal存储当前HttpServletRequest请求对象,然后后面在service或者dao层直接通过该静态ThreadLocal对象get()获取即可。
【1】利用ServletRequestListener实现
public class RequestHolder implements ServletRequestListener {
private static ThreadLocal<HttpServletRequest> httpServletRequestHolder =
new ThreadLocal<HttpServletRequest>();
@Override
public void requestInitialized(ServletRequestEvent requestEvent) {
HttpServletRequest request = (HttpServletRequest) requestEvent.getServletRequest();
httpServletRequestHolder.set(request);
}
@Override
public void requestDestroyed(ServletRequestEvent requestEvent) {
httpServletRequestHolder.remove();
}
public static HttpServletRequest getHttpServletRequest() {
return httpServletRequestHolder.get();
}
}
【2】利用Filter实现
public class RequestHolder implements Filter {
private static ThreadLocal<HttpServletRequest> httpServletRequestHolder =
new ThreadLocal<HttpServletRequest>();
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
httpServletRequestHolder.set((HttpServletRequest) request);
try {
chain.doFilter(request, response);
} catch (Exception e) {
throw e;
} finally {
httpServletRequestHolder.remove();
}
}
@Override
public void destroy() {
}
public static HttpServletRequest getHttpServletRequest() {
return httpServletRequestHolder.get();
}
}
【3】利用拦截器实现
public class RequestHolder extends HandlerInterceptorAdapter {
private static ThreadLocal<HttpServletRequest> httpServletRequestHolder =
new ThreadLocal<HttpServletRequest>();
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
httpServletRequestHolder.set(request);
return true;
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
Object handler, Exception ex)
throws Exception {
httpServletRequestHolder.remove();
}
public static HttpServletRequest getHttpServletRequest() {
return httpServletRequestHolder.get();
}
}
(3)RequestContextHolder原理分析
【1】RequestContextHolder类分析
public abstract class RequestContextHolder {
private static final ThreadLocal<RequestAttributes> requestAttributesHolder = new NamedThreadLocal("Request attributes");
private static final ThreadLocal<RequestAttributes> inheritableRequestAttributesHolder = new NamedInheritableThreadLocal("Request context");
public static void resetRequestAttributes() {
requestAttributesHolder.remove();
inheritableRequestAttributesHolder.remove();
}
public static void setRequestAttributes(@Nullable RequestAttributes attributes, boolean inheritable) {
if (attributes == null) {
resetRequestAttributes();
} else if (inheritable) {
inheritableRequestAttributesHolder.set(attributes);
requestAttributesHolder.remove();
} else {
requestAttributesHolder.set(attributes);
inheritableRequestAttributesHolder.remove();
}
}
@Nullable
public static RequestAttributes getRequestAttributes() {
RequestAttributes attributes = (RequestAttributes)requestAttributesHolder.get();
if (attributes == null) {
attributes = (RequestAttributes)inheritableRequestAttributesHolder.get();
}
return attributes;
}
public static RequestAttributes currentRequestAttributes() throws IllegalStateException {
RequestAttributes attributes = getRequestAttributes();
if (attributes == null) {
if (jsfPresent) {
attributes = RequestContextHolder.FacesRequestAttributesFactory.getFacesRequestAttributes();
}
if (attributes == null) {
throw new 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.");
}
}
return attributes;
}
}
【2】org.springframework.web.servlet.FrameworkServlet#processRequest核心处理类分析。 processRequest方法在每次请求时都会被调用执行。如上图所示各个请求类型都会去调用该方法。
protected final void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
RequestAttributes previousAttributes = RequestContextHolder.getRequestAttributes();
ServletRequestAttributes requestAttributes = this.buildRequestAttributes(request, response, previousAttributes);
WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);
asyncManager.registerCallableInterceptor(FrameworkServlet.class.getName(), new FrameworkServlet.RequestBindingInterceptor());
this.initContextHolders(request, localeContext, requestAttributes);
try {
this.doService(request, response);
}
}
【3】org.springframework.web.servlet.FrameworkServlet#initContextHolders。调用RequestContextHolder.setRequestAttributes()方法,把requestAttributes对象放入。this.threadContextInheritable默认是false。 即把HttpServletRequest的封装对象ServletRequestAttributes与当前线程绑定。
private void initContextHolders(HttpServletRequest request, @Nullable LocaleContext localeContext, @Nullable RequestAttributes requestAttributes) {
if (localeContext != null) {
LocaleContextHolder.setLocaleContext(localeContext, this.threadContextInheritable);
}
if (requestAttributes != null) {
RequestContextHolder.setRequestAttributes(requestAttributes, this.threadContextInheritable);
}
}
(4)异步子线程应用,继承父线程请求对象
如果此时我们在Service层方法中添加了 @Async注解,进行异步处理。结果如下图所示,无法获取请求对象抛出空指针异常 【1】方式一:手动在父线程设置可继承属性,子线程复用父线程请求对象。 RequestContextHolder.setRequestAttributes(RequestContextHolder.getRequestAttributes(),true); 设置可继承父请求属性。
@Autowired
private MyService myService;
@GetMapping("/get")
public String get(){
RequestContextHolder.setRequestAttributes(RequestContextHolder.getRequestAttributes(),true);
myService.process();
return "OK";
}
【2】上述方式相对来说需要在每次异步操作时进行手动设置不是很方便,而对于一般的异步处理都是通过线程池分配子线程进行处理的,所以我们也可以通过配置线程池的方式来完成该功能需求。
public class ContextAwarePoolExecutor extends ThreadPoolTaskExecutor {
@Override
public <T> Future<T> submit(Callable<T> task) {
RequestAttributes requestAttributes=null;
try{
requestAttributes = RequestContextHolder.currentRequestAttributes();
}catch (IllegalStateException e){
}
return super.submit(new ContextAwareCallable(task,requestAttributes ));
}
@Override
public <T> ListenableFuture<T> submitListenable(Callable<T> task) {
RequestAttributes requestAttributes=null;
try{
requestAttributes = RequestContextHolder.currentRequestAttributes();
}catch (IllegalStateException e) {
}
return super.submitListenable(new ContextAwareCallable(task,requestAttributes));
}
}
public class ContextAwareCallable<T> implements Callable<T> {
private Callable<T> task;
private RequestAttributes context;
public ContextAwareCallable(Callable<T> task, RequestAttributes context) {
this.task = task;
this.context = context;
}
@Override
public T call() throws Exception {
if (context != null) {
RequestContextHolder.setRequestAttributes(context);
}
try {
return task.call();
} finally {
RequestContextHolder.resetRequestAttributes();
}
}
}
配置线程池
@EnableAsync(proxyTargetClass = true)
@Configuration
public class AsycTaskExecutorConfig {
@Bean
public TaskExecutor taskExecutor() {
ThreadPoolTaskExecutor taskExecutor = new ContextAwarePoolExecutor();
taskExecutor.setCorePoolSize(50);
taskExecutor.setMaxPoolSize(100);
return taskExecutor;
}
}
经过测试可以发现可以在子线程中正常获取HTTP请求信息
|