微服務通過feign.RequestInterceptor傳遞參數


Feign 支持請求攔截器,在發送請求前,可以對發送的模板進行操作,例如設置請求頭等屬性,自定請求攔截器需要實現 feign.RequestInterceptor 接口,該接口的方法 apply 有參數 template ,該參數類型為 RequestTemplate,我們可以根據實際情況對請求信息進行調整,示例如下:

  • 創建自定義請求攔截器,在發送請求前增加了一個請求頭信息,進行身份校驗。

具體代碼參考如下:

import feign.RequestInterceptor;

import feign.RequestTemplate;

   

public class MyRequestInterceptor implements RequestInterceptor{

   

public void apply(RequestTemplatetemplate){

template.header("Authorization","123");

}

}

 服務端可以通過HttpServletRequest獲取到前面傳遞的參數,具體獲取邏輯如下:

 RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
        if (requestAttributes != null) {
            HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
            request.getHeader("Authorization");
        }

 就實現了各個微服務之間參數的傳遞。 


免責聲明!

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



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