Feign遠(yuǎn)程調(diào)用參數(shù)里面內(nèi)容丟失的解決方案
Feign遠(yuǎn)程調(diào)用參數(shù)里面內(nèi)容丟失
舉個例子
服務(wù)A提供了如下接口(注意這里的參數(shù)url是一個地址):
@GetMapping("/getSample")
public String getSample(@RequestParam String url){
?? ? //此處省略邏輯......
}服務(wù)B需要調(diào)用服務(wù)A的接口,調(diào)用如下:
sampleFeignClient.getSample("http://www.xxx.com?name=dumas&age=18");提出問題:此時調(diào)用服務(wù)A接口后,在A服務(wù)接收的方法體內(nèi),斷點(diǎn)會發(fā)現(xiàn)后面的參數(shù)age=18會丟失。
問題的原因:Feign遠(yuǎn)程調(diào)用是使用HTTP協(xié)議的,可能是獲取參數(shù)的時候,把參數(shù)url里面的內(nèi)容當(dāng)成了參數(shù),所以直接舍棄了。
解決方法
服務(wù)B調(diào)用前,使用URLEncoder.encode(url,"UTF-8");
服務(wù)A獲取參數(shù)后,使用URLDecoder.decode(url, "UTF-8");
Feign遠(yuǎn)程調(diào)用細(xì)節(jié)--丟失數(shù)據(jù)
同步調(diào)用
我這里只添加了header中的Cookie,當(dāng)然也可以遍歷header,把所有的都添加到新的請求,解決辦法跟Gateway丟失請求頭類似。
@Configuration
public class FeignConfiguration {
? ? //feign遠(yuǎn)程調(diào)用丟失請求頭問題
? ? @Bean("requestInterceptor")
? ? public RequestInterceptor requestInterceptor(){
? ? ? ? return template -> {
? ? ? ? ? ? ServletRequestAttributes attributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
? ? ? ? ? ? HttpServletRequest request = attributes.getRequest();
? ? ? ? ? ? String cookie = request.getHeader("Cookie");
? ? ? ? ? ? template.header("Cookie",cookie);
? ? ? ? };
? ? }
}異步調(diào)用
當(dāng)我們使用異步調(diào)用openfeign,上述代碼就會報空指針,獲取不到當(dāng)前的請求。
我們先獲取到當(dāng)前請求,再分享給子線程。
RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
? ? RequestContextHolder.setRequestAttributes(attributes);
? ? feign.doService();
}, executor);以上為個人經(jīng)驗(yàn),希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
解決SpringMvc中普通類注入Service為null的問題
這篇文章主要介紹了解決SpringMvc中普通類注入Service為null的問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-07-07
JAVA 實(shí)現(xiàn)延遲隊(duì)列的方法
這篇文章主要介紹了JAVA 實(shí)現(xiàn)延遲隊(duì)列的方法,文中講解非常詳細(xì),供大家參考和學(xué)習(xí),感興趣的朋友可以了解下2020-06-06

