Implementation scheme

Implementation RequestInterceptor intercepts every Feign request, add a Token

RequestInterceptorFeign intercept


/** * Feign request blocking **@author Tan
 * @version1.0 2021/1/7 * /
@Slf4j
@Component // Inject beans, which can also be configured using configuration properties
public class FeignRequestInterceptor implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate template) {
        log.info("Feign call, URL: {}", template.request().url());

        HttpServletRequest request = Optional.ofNullable(RequestContextHolder.getRequestAttributes()).map(it -> ((ServletRequestAttributes) it).getRequest()).orElse(null);
        if (request == null) {
            return;
        }
        Iterator<String> headerIterator = CollectionUtils.toIterator(request.getHeaderNames());
        while (headerIterator.hasNext()) {
            String name = headerIterator.next();
            log.info("add header, url: {} , path: {}", name, request.getHeader(name));
            // Write only Authorization
            if(BaseConstants.HEADER_KEY_TOKEN.equals(name)) { template.header(name, request.getHeader(name)); }}}}Copy the code

Configuration mode

  • 1. Use@ComponentInject beans, as shown in the code example
  • 2. Configure the parameters using the configuration properties
feign:
  client:
    config:
      feignName:
        requestInterceptors:
          - com.example.FeignRequestInterceptor
Copy the code

The official documentation