1.feign的使用场景
注意:谁发起feign的请求,feign的拦截器就定义在谁身上,拦截器的目的是为了传递令牌。
2.使用步骤:
(1)创建拦截器
在changgou_common服务中创建一个com.changgou.interceptor.FeignInterceptor拦截器,并将所有头文件数据再次加入到Feign请求的微服务头文件中,代码如下:
@Component public class FeignInterceptor implements RequestInterceptor { @Override public void apply(RequestTemplate requestTemplate) { RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes(); if (requestAttributes!=null){ HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest(); if (request!=null){ Enumeration<String> headerNames = request.getHeaderNames(); if (headerNames!=null){ while (headerNames.hasMoreElements()){ String headerName = headerNames.nextElement(); if (headerName.equals("authorization")){ String headerValue = request.getHeader(headerName); requestTemplate.header(headerName,headerValue);//核心代码 } } } } } } }
2) 更改changgou_order_web启动类,添加拦截器声明(谁发起feign的请求,就把feign拦截器放在谁上面)
@Bean public FeignInterceptor feignInterceptor(){ return new FeignInterceptor(); }