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() {
        return new MyClientInterceptor();
    }

}

//攔截器實現
class MyClientInterceptor implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate requestTemplate) {
        requestTemplate.query("name","Allen") ;
    }
    
}

配置類指定我們的自定義攔截器,攔截器需要繼承RequestInterceptor,實現 apply(RequestTemplate requestTemplate) 方法。在這個方法我們拿到了被攔截請求的RestTemplate實例,就可以往里面扔公共參數啦~

在這里調用query,就是追加一個新的query param,還有其他api如header、body等等,按需調用即可。

如果處理比較簡單,我們可以利用Lambda直接在配置類編寫匿名內部類,代碼看起來簡潔得多。

public class MyConfig {

    @Bean
    public RequestInterceptor requestInterceptor() {
        return template -> template.query("name", "Allen");
    }
    
}

Feign可以配置多個攔截器,但Spring並不保證其執行順序。

Zero or more {@code RequestInterceptors} may be configured for purposes such as adding headers to
all requests. No guarantees are give with regards to the order that interceptors are applied.


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM