使用场景:html
在springcloud中经过Fegin调用远端RestApi的时候,常常须要传递一些参数信息到被调用服务中去,好比从A服务调用B服务的时候,
须要将当前用户信息传递到B调用的服务中去,咱们就能够使用实现 RequestInterceptor接口,完成FeginClient 请求调用时拦截请求的统一处理请求头,添加请求头信息等;spring
@Slf4j @Component public class DtsInterceptor implements RequestInterceptor { @Override public void apply(RequestTemplate requestTemplate) { //TODO 作一些业务处理,获取数据,添加数据到请求头 requestTemplate.header(key,value); } }
在被调用服务中获取请求头app
第一种方式:ide
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); try { request.setCharacterEncoding(“UTF-8”); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } String sUserInfo = request.getHeader(KEY);
第二种方式:post
配置Spring MVC的拦截器(Interceptor),能够自定义实现HandlerInterceptor
接口,也能够经过继承HandlerInterceptorAdapter
类,后者是前者的实现类。spa
public class UserInterceptor extends HandlerInterceptorAdapter { /** 预处理回调方法,实现处理器的预处理(如登陆检查)。 * 第三个参数为响应的处理器,即controller。 * 返回true,表示继续流程,调用下一个拦截器或者处理器。 * 返回false,表示流程中断,经过response产生响应。 * */ @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { String key = request.getHeader("key"); if(StringUtils.isNotBlank(key)){ return false ; }else { //TODO 解析key为用户信息,解析成功返回true,解析失败返回false return true ; } } /** *当前请求进行处理以后,也就是Controller 方法调用以后执行, *可是它会在DispatcherServlet 进行视图返回渲染以前被调用。 *此时咱们能够经过modelAndView对模型数据进行处理或对视图进行处理。
*/ @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { super.postHandle(request, response, handler, modelAndView); } /** *方法将在整个请求结束以后,也就是在DispatcherServlet 渲染了对应的视图以后执行。 *这个方法的主要做用是用于进行资源清理工做的。 */ @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { super.afterCompletion(request, response, handler, ex); }
为了使自定义的拦截器生效,须要注册拦截器到spring容器中,具体的作法是继承
WebMvcConfigurerAdapter
类,覆盖其
addInterceptors(InterceptorRegistry registry)
方法。最后别忘了把Bean注册到Spring容器中,能够选择@Component 或者 @Configuration。
@Component public class InterceptorConfiguration extends WebMvcConfigurerAdapter { @Override public void addInterceptors(InterceptorRegistry registry) { // 注册拦截器 InterceptorRegistration interceptorRegistration = registry.addInterceptor(new UserInterceptor()); // 配置拦截的路径 interceptorRegistration.addPathPatterns("/**"); // 配置不拦截的路径 interceptorRegistration.excludePathPatterns("/**.html"); // 还能够在这里注册其它的拦截器 // registry.addInterceptor(new OtherInterceptor()).addPathPatterns("/**");
super.addInterceptors(registry); } }