1. 问题

在项目中以如下方式定义了一个 FeignClient:

import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Component
@FeignClient(name = "user")
public interface UserInterfaces {
    @PostMapping("/user/deleteUsers")
    void deleteUsers(@RequestParam List<Integer> userIds);
}

但是user模块接口设置了拦截器或者Spring Security,导致调用失败。

2. 解决方案

可以通过RequestInterceptor来添加拦截器,如下:

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Enumeration;

@Configuration
public class FeignInterceptorConfig implements RequestInterceptor {

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

这样就可以将FeignClient调用时的请求头信息传递给user模块。