Feign拦截器传递请求头信息

方式一:

1.创建FeignInterceptor配置类

public class FeignInterceptorConfig {
    @Bean
    public RequestInterceptor requestInterceptor() {
        return template -> {
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder
                    .getRequestAttributes();
            if (attributes != null) {
                HttpServletRequest request = attributes.getRequest();
                Enumeration headerNames = request.getHeaderNames();
                if (headerNames != null) {
                    String headerName;
                    String headerValue;
                    while(headerNames.hasMoreElements()) {
                        headerName = headerNames.nextElement();
                        if (requestHeaders.contains(headerName)) {
                            headerValue = request.getHeader(headerName);
                            template.header(headerName, headerValue);
                        }
                    }
                }
            }
   
        };
    }
}

2.在启动类上加 @Import(FeignInterceptorConfig.class)

方式二

1.实现RequestInterceptor接口

public class FeignRequestInterceptor implements RequestInterceptor {
  @Override
  public void apply(RequestTemplate requestTemplate) {
    ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder
            .getRequestAttributes();
    HttpServletRequest request = attributes.getRequest();
    Enumeration headerNames = request.getHeaderNames();
    if (headerNames != null) {
      while (headerNames.hasMoreElements()) {
        String name = headerNames.nextElement();
        String values = request.getHeader(name);
        requestTemplate.header(name, values);
      }
    }
  }
}

2.创建全局配置类

@Configuration
public class FeignInterceptorConfig {
  /**
   * feign请求拦截器
   */
  @Bean
  public RequestInterceptor requestInterceptor(){
    return new FeignRequestInterceptor();
  }
}

你可能感兴趣的:(Feign拦截器传递请求头信息)