跳到主要内容

【22】RequestInterceptor获取不到HttpServletRequest问题解决方案

文章目录

  • 问题场景
  • 原因分析
    • RequestContextHolder
  • Hystrix隔离策略
  • 解决方案
    • 方案1 修改隔离策略为SEMAPHORE
  • 方案2 自定义隔离策略

问题场景

在使用Hystrix的情况下,使用RequestInterceptor获取Oauth2 令牌并传递到下游服务时,发现从RequestContextHolder中获取到的HttpServletRequest为NULL。

@Component
public class AAOauth2TokenRequestInterceptor implements RequestInterceptor {



@Override
public void apply(RequestTemplate requestTemplate) {


// 1. 获取 HttpServletRequest
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
}
}

原因分析

RequestContextHolder

RequestContextHolder 请求上下文持有者,可以看到在其ThreadLocal中,保存了请求对象,我们可以在当前线程的任意位置,通过这个类来获取到当前请求的RequestAttributes
 

Hystrix隔离策略

Hystrix提供了两个隔离策略:THREADSEMAPHORE。其默认的策略为THREAD(线程池)。

在执行请求的实际,可以看到其代理对象是通过HystrixInvocationHandler实现的,首先会创建一个HystrixCommand对象。