Spring Cloud Feign 拦截器,Java后端开发面试问题
Spring Cloud Feign 提供了一种简单的方式来定义和配置HTTP请求的拦截器。你可以通过实现FeignBuilder
接口来创建自定义的Feign客户端构建器,并注册拦截器。
下面是一个简单的例子,展示如何在Spring Cloud Feign中添加一个自定义拦截器:
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.Collections;
@Configuration
public class FeignConfig {
@Bean
public RequestInterceptor requestInterceptor() {
return new RequestInterceptor() {
@Override
public void apply(RequestTemplate template) {
// 在这里添加拦截逻辑,比如添加header
template.header("Custom-Header", "value");
}
};
}
}
在Feign客户端接口中使用:
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
@FeignClient(name = "example-service", configuration = FeignConfig.class)
public interface ExampleServiceClient {
@GetMapping("/endpoint")
String getData();
}
在上面的例子中,FeignConfig
类定义了一个RequestInterceptor
,它会在每个Feign请求中添加一个自定义的header。然后,在Feign客户端接口上使用configuration
属性来指定这个配置类。这样,所有通过ExampleServiceClient
发出的请求都会被这个拦截器所处理。
评论已关闭