如何实现调用其他服务默认添加请求参数,包括feign调用?
实现OncePerRequestFilter接口
OncePerRequestFilter接口就是每次发起请求,确保只会执行一次。
- 自定义创建会话上下文 MyRequestContext.java,可以在我们需要的时候就直接拿出来使用,请求结束就应该清除对象
public class MyRequestContext {
public static final String USER_ID = "user_id";
public static final String ACCESS_TOKEN = "accessToken";
public static final String PROTOCOL_SCHEME = "Protocol-Scheme";
private static final ThreadLocal<Map<String, Object>> USER_LOCAL = new InheritableThreadLocal<Map<String, Object>>();
private MyRequestContext() {
}
public static Object get(String key) {
return ((Map)USER_LOCAL.get()).get(key);
}
public static void put(String key, Object value) {
((Map)USER_LOCAL.get()).put(key, value);
}
public static void remove() {
USER_LOCAL.remove();
}
public static Map<String, Object> getAll() {
return (Map)USER_LOCAL.get();
}
}
- 过滤器中维护上下文 MyRequestContext.java
public class RequestLinkContextFilter extends OncePerRequestFilter {
private static final Logger log = LoggerFactory.getLogger(RequestLinkContextFilter.class);
public RequestLinkContextFilter() {
}
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
String userId = request.getHeader("user_id");
if (StringUtils.isNotBlank(userId)) {
MyRequestContext.put("user_id", Long.parseLong(userId));
}
String accessToken = request.getHeader("accessToken");
if (StringUtils.isNotBlank(accessToken)) {
MyRequestContext.put("accessToken", accessToken);
}
String protocolScheme = request.getHeader("Protocol-Scheme");
if (StringUtils.isNotBlank(protocolScheme)) {
MyRequestContext.put("Protocol-Scheme", protocolScheme);
}
String originFrom = request.getHeader("origin-from");
if (StringUtils.isNotBlank(originFrom)) {
MyRequestContext.put("origin-from", originFrom);
}
try {
chain.doFilter(request, response);
} finally {
MyRequestContext.remove();
}
}
}
feign调用也需要实现传递参数
- 实现接口RequestInterceptor.java
public class MyFeignInterceptor implements RequestInterceptor {
public MyFeignInterceptor() {
}
public void apply(RequestTemplate template) {
Map<String, Object> allContext = MyRequestContext.getAll();
if (!MapUtils.isEmpty(allContext)) {
Iterator var3 = allContext.entrySet().iterator();
while(var3.hasNext()) {
Entry<String, Object> entry = (Entry)var3.next();
if (entry.getValue() instanceof String) {
template.header((String)entry.getKey(), new String[]{entry.getValue().toString()});
} else {
template.header((String)entry.getKey(), new String[]{JSON.toJSONString(entry.getValue())});
}
}
}
}
}
RestTemplate(Ribbon)拦截器
- 实现接口ClientHttpRequestInterceptor.java
public class MyHttpRequestInterceptor implements ClientHttpRequestInterceptor {
public MyHttpRequestInterceptor() {
}
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
HttpHeaders headers = request.getHeaders();
Map<String, Object> allContext = MyRequestContext.getAll();
if (MapUtils.isEmpty(allContext)) {
return execution.execute(request, body);
} else {
Iterator var6 = allContext.entrySet().iterator();
while(var6.hasNext()) {
Entry<String, Object> entry = (Entry)var6.next();
if (!headers.containsKey(entry.getKey())) {
if (entry.getValue() instanceof String) {
headers.add((String)entry.getKey(), entry.getValue().toString());
} else {
headers.add((String)entry.getKey(), JSON.toJSONString(entry.getValue()));
}
}
}
return execution.execute(request, body);
}
}
}
加入spring容器即可生效
拦截总结
springMVC项目,网页请求拦截
HandlerInterceptor是最常规的,其拦截的http请求是来自于客户端浏览器之类的,是最常见的http请求拦截器
public class LoginFilter extends HandlerInterceptorAdapter {
private final Logger logger = LoggerFactory.getLogger(LoginFilter.class);
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
logger.info("request请求地址path[{}] uri[{}]", request.getServletPath(),request.getRequestURI());
Long userId= getUserId(request.getHeader("H-User-Token"));
if (userId != null && checkAuth(userId,request.getRequestURI())){
return true;
}
throw new FastRuntimeException(20001,"No access");
}
private Long getUserId(String userToken){
Long userId = null;
return userId;
}
private boolean checkAuth(Long userId,String requestURI){
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
throws Exception {}
}
springBoot项目,RestTemplate/Ribbon请求拦截
- ClientHttpRequestInterceptor
ClientHttpRequestInterceptor是对RestTemplate的请求进行拦截的,在项目中直接使用restTemplate.getForObject的时候,会对这种请求进行拦截,经常被称为:RestTempalte拦截器或者Ribbon拦截器;
OpenFeign调用拦截
RequestInterceptor常被称为是Feign拦截器,由于Feign调用底层实际上还是http调用,因此也是一个http拦截器,在项目中使用Feign调用的时候,可以使用此拦截器
|