给feign接口设置拦截器

步骤1:创建 Interceptor

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
@Component
@Slf4j
public class InternalRequestInterceptor implements RequestInterceptor {

    @Value("${spring.application.name:unknown}")
    private String serviceName;

    @Override
    public void apply(RequestTemplate template) {
        log.debug("Applying internal request headers for: {}", template.url());

        template.header("X-Internal-Request", "true");
        template.header("X-Service-Name", serviceName);
        template.header("X-Request-ID", UUID.randomUUID().toString());
        template.header("X-Timestamp", String.valueOf(System.currentTimeMillis()));
    }
}

步骤2:确保 Spring 配置正确

1
2
3
4
5
6
7
@SpringBootApplication
@EnableFeignClients // 这个注解必须要有!
public class OrderServiceApplication {
    public static void main(String[] args) {
        SpringApplication.run(OrderServiceApplication.class, args);
    }
}

步骤3:验证配置

创建测试类验证:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
@SpringBootTest
public class FeignInterceptorTest {

    @Autowired
    private UserServiceClient userServiceClient;

    @MockBean
    private UserServiceClient mockUserServiceClient; // 用于模拟

    @Test
    public void testInterceptorRegistration() {
        // 检查Interceptor是否被Spring管理
        Map<String, RequestInterceptor> interceptors = 
        applicationContext.getBeansOfType(RequestInterceptor.class);

        assertThat(interceptors).isNotEmpty();
        assertThat(interceptors.values())
        .anyMatch(interceptor -> interceptor instanceof InternalRequestInterceptor);
    }
}

高级配置 - 使用自定义 Feign Builder

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
@Configuration
public class CustomFeignConfig {

    @Autowired
    private List<RequestInterceptor> requestInterceptors;

    @Bean
    public Feign.Builder feignBuilder() {
        return Feign.builder()
        .requestInterceptors(requestInterceptors)
        .logger(new Slf4jLogger())
        .logLevel(Logger.Level.FULL);
    }
}

如果该拦截器和配置类是作为核心包被其他模块引入的

在核心包创建resources/META-INF/spring.factories

1
2
3
4
5
6
7
# META-INF/spring.factories
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
  com.yourcompany.common.config.CommonFeignConfig,\
  com.yourcompany.common.interceptor.CommonRequestInterceptor

org.springframework.cloud.openfeign.FeignClientSpecification=\
  com.yourcompany.common.config.CommonFeignConfig

或者说spring为3.+版本 , 使用resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports文件

1
2
3
com.yourcompany.common.config.CommonFeignConfig
com.yourcompany.common.interceptor.CommonRequestInterceptor
com.yourcompany.common.config.CommonFeignConfig

检查 Interceptor 是否生效的调试方法

方法1:查看启动日志

在应用启动时,查看是否有这样的日志:

1
2
Registered Feign client [UserServiceClient]
Found RequestInterceptor [internalRequestInterceptor]

方法2:启用调试日志

1
2
3
4
logging:
  level:
    org.springframework.cloud.openfeign: DEBUG
    feign: DEBUG

方法3:添加调试代码

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
@Component
public class DebugInterceptor implements RequestInterceptor {

    @PostConstruct
    public void init() {
        System.out.println("Feign Interceptor initialized and registered!");
    }

    @Override
    public void apply(RequestTemplate template) {
        System.out.println("Interceptor applied to: " + template.url());
        System.out.println("Headers: " + template.headers());
    }
}