在我们通过OpenFeign调用接口,在调用接口前,如果想在请求中添加一些header信息、打一些日志等操作如何做呢?OpenFeign为我们提供了请求拦截器RequestInterceptor,我们可以通过实现这个接口,完成自己的拦截器功能,并配置到指定的Feign客户端。
配置方式
1.@Configuration方式
public class ProviderClientConfiguration {@Beanpublic BasicAuthRequestInterceptor basicAuthRequestInterceptor() {return new BasicAuthRequestInterceptor("gaoxi", "password");}}@FeignClient(name = "provider-nacos",contextId ="provider",fallbackFactory = ProviderClientFallbackFactory.class,configuration = ProviderClientConfiguration.class)public interface ProviderClient {@GetMapping("test")String test();}
服务提供方可以通过取header中的
Basic字段获取
2.Yaml方式
这种方式我知道可以配置无参构造方法的拦截器,但是拦截器构造方法需要参数的话,这边我也不知道怎么去配置
feign:client:config:default:loggerLevel: BASICrequestInterceptors:- com.gao.consumernacosdemotimeout.config.CustomInterceptor
自定义请求拦截器
自定义请求拦截器的话可以参考OpenFeign为我们实现好的一些拦截器`BasicAuthRequestInterceptor`,然后学着写一下就好。
public class CustomInterceptor implements RequestInterceptor {private static final Logger logger = LoggerFactory.getLogger(CustomInterceptor.class);@Overridepublic void apply(RequestTemplate template) {logger.info("自定义请求拦截器");template.header("name", "gaoxi");}}
然后配置一下即可
feign:client:config:default:loggerLevel: BASICrequestInterceptors:- com.gao.consumernacosdemotimeout.config.CustomInterceptor或者public class ProviderClientConfiguration {@Beanpublic BasicAuthRequestInterceptor basicAuthRequestInterceptor() {return new BasicAuthRequestInterceptor("gaoxi", "password");}@Beanpublic CustomInterceptor customInterceptor(){return new CustomInterceptor();}}
注意: 若@Configuration和yaml中都有配置的话,两者都可以被应用上
