@FeignClient?path屬性路徑前綴帶路徑變量時(shí)報(bào)錯(cuò)的解決
@FeignClient path屬性路徑前綴帶路徑變量時(shí)報(bào)錯(cuò)
現(xiàn)象
FeignClient注解中使用path屬性定義url前綴時(shí),如果使用了路徑變量,則會(huì)報(bào)錯(cuò)
例如
@FeignClient(name = "user-api", path = "/api/user/{id}")
報(bào)錯(cuò)
ERROR o.a.c.c.C.[.[localhost].[/].[dispatcherServlet] - Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.IllegalArgumentException: Target is not a valid URI.] with root cause
java.net.URISyntaxException: Illegal character in path at index 25: http://user-api/api/user/{id}
源碼分析
feign.Target
注:url成員值為@FeignClient配置的path屬性值
public interface Target<T> { ?? ?@Override ? ? public Request apply(RequestTemplate input) { ? ? ? if (input.url().indexOf("http") != 0) { ? ? ? ? input.target(url()); ? ? ? } ? ? ? return input.request(); ? ? } }
feign.RequestTemplate
注:此處將path屬性值直接解析為URI對(duì)象,如果包含形如{PathVariable}的路徑變量,會(huì)導(dǎo)致解析異常
public final class RequestTemplate implements Serializable { ? public RequestTemplate target(String target) { ? ? /* target can be empty */ ? ? if (Util.isBlank(target)) { ? ? ? return this; ? ? } ? ? /* verify that the target contains the scheme, host and port */ ? ? if (!UriUtils.isAbsolute(target)) { ? ? ? throw new IllegalArgumentException("target values must be absolute."); ? ? } ? ? if (target.endsWith("/")) { ? ? ? target = target.substring(0, target.length() - 1); ? ? } ? ? try { ? ? ? /* parse the target */? ? ? ? // 此處直接將path ? ? ? URI targetUri = URI.create(target); ? ? ? if (Util.isNotBlank(targetUri.getRawQuery())) { ? ? ? ? /* ? ? ? ? ?* target has a query string, we need to make sure that they are recorded as queries ? ? ? ? ?*/ ? ? ? ? this.extractQueryTemplates(targetUri.getRawQuery(), true); ? ? ? } ? ? ? /* strip the query string */ ? ? ? this.target = targetUri.getScheme() + "://" + targetUri.getAuthority() + targetUri.getPath(); ? ? ? if (targetUri.getFragment() != null) { ? ? ? ? this.fragment = "#" + targetUri.getFragment(); ? ? ? } ? ? } catch (IllegalArgumentException iae) { ? ? ? /* the uri provided is not a valid one, we can't continue */ ? ? ? throw new IllegalArgumentException("Target is not a valid URI.", iae); ? ? } ? ? return this; ? } }
解決辦法
如需使用路徑變量使用@RequestMapping代替Path
@FeignClient(name = "user-api") @RequestMapping("/api/user/{id}")
@FeignClient使用詳解
@FeignClient標(biāo)簽的常用屬性如下
name
:指定FeignClient的名稱(chēng),如果項(xiàng)目使用了Ribbon,name屬性會(huì)作為微服務(wù)的名稱(chēng),用于服務(wù)發(fā)現(xiàn)url
: url一般用于調(diào)試,可以手動(dòng)指定@FeignClient調(diào)用的地址decode404
:當(dāng)發(fā)生http 404錯(cuò)誤時(shí),如果該字段位true,會(huì)調(diào)用decoder進(jìn)行解碼,否則拋出FeignExceptionconfiguration
: Feign配置類(lèi),可以自定義Feign的Encoder、Decoder、LogLevel、Contractfallback
: 定義容錯(cuò)的處理類(lèi),當(dāng)調(diào)用遠(yuǎn)程接口失敗或超時(shí)時(shí),會(huì)調(diào)用對(duì)應(yīng)接口的容錯(cuò)邏輯,fallback指定的類(lèi)必須實(shí)現(xiàn)@FeignClient標(biāo)記的接口fallbackFactory
: 工廠類(lèi),用于生成fallback類(lèi)示例,通過(guò)這個(gè)屬性我們可以實(shí)現(xiàn)每個(gè)接口通用的容錯(cuò)邏輯,減少重復(fù)的代碼path
: 定義當(dāng)前FeignClient的統(tǒng)一前綴,當(dāng)我們項(xiàng)目中配置了server.context-path,server.servlet-path時(shí)使用
1.首先
我們?cè)趩?dòng)類(lèi)里面加入注解,聲明開(kāi)啟Feign的遠(yuǎn)程調(diào)用,如下:
@EnableEurekaClient @SpringBootApplication @EnableFeignClients public class LoginStart { ?? ?public static void main(String[] args) { ?? ??? ?SpringApplication.run(LoginStart.class, args); ?? ?} }
2.編寫(xiě)接口類(lèi)
value="/xxx/xxx"就是我們服務(wù)方暴露的接口地址,如下:
import java.util.List; import org.springframework.cloud.netflix.feign.FeignClient; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; ? @FeignClient(name="custorm",fallback=Hysitx.class) public interface IRemoteCallService { ?? ?@RequestMapping(value="/custorm/getTest",method = RequestMethod.POST) ? ? List<String> test(@RequestParam("names") String[] names); }
3.編寫(xiě)熔斷類(lèi)
發(fā)生錯(cuò)誤時(shí)回調(diào):
import java.util.List; import org.springframework.stereotype.Component; @Component public class Hysitx implements IRemoteCallService{ ?? ?@Override ?? ?public List<String> test(String[] names) { ?? ??? ?System.out.println("接口調(diào)用失敗"); ?? ??? ?return null; ?? ?} }
4.然后我們準(zhǔn)備兩個(gè)消費(fèi)者工程
custorm(服務(wù)方),login(調(diào)用方),然后在login的controller中寫(xiě)前臺(tái)調(diào)用接口:
@Autowired private IRemoteCallService remot; ?? ? @RequestMapping("/config") public String config() { ?? ?String[] names = {"王五","張柳"}; ?? ?return remot.test(names).toString(); }
5.然后在custorm工程中寫(xiě)一個(gè)接口
在這個(gè)接口里我們只將傳輸進(jìn)來(lái)的數(shù)據(jù)再添加一個(gè)數(shù)據(jù)返回回去
@RestController @RequestMapping("/custorm") public class CustormController { ?? ? ? ? @RequestMapping("/getTest") ? ? public List<String> Test(String[] names) { ? ? ?? ?List<String> name = new ArrayList<String>(Arrays.asList(names)); ? ? ?? ?name.add("王麻子"); ? ? ?? ?return name; ? ? } }
6.然后我們啟動(dòng)注冊(cè)中心
配置中心以及兩個(gè)消費(fèi)者服務(wù),需要了解配置中心和注冊(cè)中心的搭建可以看我前兩篇文章,啟動(dòng)后瀏覽器我們進(jìn)行訪(fǎng)問(wèn)
可以看到,返回的數(shù)據(jù)中已經(jīng)包含了custorm工程中拼接的數(shù)據(jù),說(shuō)明我們遠(yuǎn)程調(diào)用接口成功,以上就是feign的簡(jiǎn)單使用
另外補(bǔ)充一些面試中長(zhǎng)問(wèn)的如何給@FeignClient添加Header信息
1.在@RequestMapping中添加,如下:
@FeignClient(name="custorm",fallback=Hysitx.class) public interface IRemoteCallService { @RequestMapping(value="/custorm/getTest",method = RequestMethod.POST, headers = {"Content-Type=application/json;charset=UTF-8"}) List<String> test(@RequestParam("names") String[] names); }
2.在方法參數(shù)前面添加@RequestHeader注解,如下:
@FeignClient(name="custorm",fallback=Hysitx.class) public interface IRemoteCallService { @RequestMapping(value="/custorm/getTest",method = RequestMethod.POST, headers = {"Content-Type=application/json;charset=UTF-8"}) List<String> test(@RequestParam("names")@RequestHeader("Authorization") String[] names); }
設(shè)置多個(gè)屬性時(shí),可以使用Map,如下:
import java.util.List; import org.springframework.cloud.netflix.feign.FeignClient; import org.springframework.util.MultiValueMap; import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; @FeignClient(name="custorm",fallback=Hysitx.class) public interface IRemoteCallService { @RequestMapping(value="/custorm/getTest",method = RequestMethod.POST, headers = {"Content-Type=application/json;charset=UTF-8"}) List<String> test(@RequestParam("names") String[] names, @RequestHeader MultiValueMap<String, String> headers); }
3.使用@Header注解,如下:
@FeignClient(name="custorm",fallback=Hysitx.class) public interface IRemoteCallService { @RequestMapping(value="/custorm/getTest",method = RequestMethod.POST) @Headers({"Content-Type: application/json;charset=UTF-8"}) List<String> test(@RequestParam("names") String[] names); }
4.實(shí)現(xiàn)RequestInterceptor接口,如下:
@Configuration public class FeignRequestInterceptor implements RequestInterceptor { @Override public void apply(RequestTemplate temp) { temp.header(HttpHeaders.AUTHORIZATION, "XXXXX"); } }
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
- springcloud-feign調(diào)用報(bào)錯(cuò)問(wèn)題
- 如何解決使用restTemplate進(jìn)行feign調(diào)用new HttpEntity<>報(bào)錯(cuò)問(wèn)題
- 解決Spring調(diào)用Feign報(bào)錯(cuò):java.io.IOException:Incomplete output stream問(wèn)題
- 通過(guò)FeignClient調(diào)用微服務(wù)提供的分頁(yè)對(duì)象IPage報(bào)錯(cuò)的解決
- 使用feign發(fā)送http請(qǐng)求解析報(bào)錯(cuò)的問(wèn)題
- Springcloud?feign傳日期類(lèi)型參數(shù)報(bào)錯(cuò)的解決方案
- 解決配置Feign時(shí)報(bào)錯(cuò)PathVariable annotation was empty on param 0.
相關(guān)文章
實(shí)戰(zhàn)分布式醫(yī)療掛號(hào)通用模塊統(tǒng)一返回結(jié)果異常日志處理
這篇文章主要為大家介紹了實(shí)戰(zhàn)分布式醫(yī)療掛號(hào)系統(tǒng)之統(tǒng)一返回結(jié)果統(tǒng)一異常處理,統(tǒng)一日志處理到通用模塊示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助2022-04-04SpringBoot超詳細(xì)講解多數(shù)據(jù)源集成
今天分享下SpringBoot多數(shù)據(jù)源集成,我怕麻煩,這里我覺(jué)得我的集成也應(yīng)該是最簡(jiǎn)單的,清晰明了2022-05-05在Spring Boot中使用swagger-bootstrap-ui的方法
這篇文章主要介紹了在Spring Boot中使用swagger-bootstrap-ui的方法,需要的朋友可以參考下2018-01-01Java中的static和final關(guān)鍵字的使用詳解
這篇文章主要介紹了Java中的static和final關(guān)鍵字的使用詳解, 當(dāng)方法名前有static,即為static方法,可以方便我們無(wú)需創(chuàng)建對(duì)象也可以調(diào)用此方法,靜態(tài)方法比較拉,只可以訪(fǎng)問(wèn) 靜態(tài)的 屬性/變量/方法,無(wú)法訪(fǎng)問(wèn)非靜態(tài)的這些屬性/變量/方法,需要的朋友可以參考下2024-01-01Java獲取Jar、War包路徑并生成可編輯修改的本地配置文件
這篇文章主要給大家介紹了關(guān)于Java如何獲取Jar、War包路徑并生成可編輯修改的本地配置文件,文中通過(guò)代碼介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者使用Java具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2024-01-01SpringBoot 整合WebSocket 前端 uniapp 訪(fǎng)問(wèn)的詳細(xì)方法
這篇文章主要介紹了SpringBoot 整合WebSocket 前端 uniapp 訪(fǎng)問(wèn)的詳細(xì)方法,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-09-09