feign调用走不走网关全局拦截_Feign Interceptor 拦截器实现全局请求参数

背景

在第三方API对接中通常所有接口都需要在Header或Param放置固定参数(Token、开发者Key等),因为是SpringCloud开发,一般HTTP工具采用Feign。如果选择每个方法都copy相应字段,显得较为冗余。这个时候就可以使用Feign的Interceptor功能。

实现

Talk is cheap,show me the code.

下面选择一个具体场景,需要某个FeignClient内所有接口都带上一个查询字符串:name=Allen

@FeignClient(value = "example", url = "https://api.xxx.com",configuration = MyConfig.class)

public interface ExampleClient {

@PutMapping(value = "/a")

AddRes add(@RequestParam("id") String id);

@DeleteMapping(value = "/b")

DelRes delete(@RequestParam("id") String id);

}

在@FeignClient注解的configuration参数指定一个配置类,下面是这个配置类的实现

public class MyConfig {

@Bean("myInterceptor")

public RequestInterceptor getRequestInterceptor() {

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Feign是一个用于调用REST API的Java库,可以用来简化HTTP客户端的开发。在Feign中,我们可以通过实现ResponseInterceptor接口来实现响应拦截器。 响应拦截器包含了一个方法,即interceptResponse()方法。该方法会在Feign接收到响应后被调用,可以用来对响应进行处理,例如对响应进行日志记录、对响应进行加工等操作。 下面是一个简单的响应拦截器的示例: ```java public class MyResponseInterceptor implements ResponseInterceptor { @Override public void interceptResponse(Response response) { // 对响应进行处理 System.out.println(response.body()); } } ``` 在上面的代码中,我们通过实现ResponseInterceptor接口,并重写interceptResponse()方法来实现响应拦截器。在interceptResponse()方法中,我们可以通过Response对象来获取响应的内容,并进行相应的处理。 在使用Feign时,我们可以将响应拦截器添加到Feign的构建器中,例如: ```java MyResponseInterceptor interceptor = new MyResponseInterceptor(); MyApi api = Feign.builder() .target(MyApi.class, "https://myapi.com") .requestInterceptor(new MyRequestInterceptor()) .responseInterceptor(interceptor) .build(); ``` 在上面的代码中,我们将MyResponseInterceptor添加到了Feign的构建器中,并通过responseInterceptor()方法来添加。这样,在每次Feign接收到响应后,都会调用MyResponseInterceptor中的interceptResponse()方法来进行响应处理。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值