@FeignClient?path屬性路徑前綴帶路徑變量時報錯的解決
@FeignClient path屬性路徑前綴帶路徑變量時報錯
現(xiàn)象
FeignClient注解中使用path屬性定義url前綴時,如果使用了路徑變量,則會報錯
例如
@FeignClient(name = "user-api",
path = "/api/user/{id}")報錯
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對象,如果包含形如{PathVariable}的路徑變量,會導致解析異常
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標簽的常用屬性如下
name:指定FeignClient的名稱,如果項目使用了Ribbon,name屬性會作為微服務(wù)的名稱,用于服務(wù)發(fā)現(xiàn)url: url一般用于調(diào)試,可以手動指定@FeignClient調(diào)用的地址decode404:當發(fā)生http 404錯誤時,如果該字段位true,會調(diào)用decoder進行解碼,否則拋出FeignExceptionconfiguration: Feign配置類,可以自定義Feign的Encoder、Decoder、LogLevel、Contractfallback: 定義容錯的處理類,當調(diào)用遠程接口失敗或超時時,會調(diào)用對應(yīng)接口的容錯邏輯,fallback指定的類必須實現(xiàn)@FeignClient標記的接口fallbackFactory: 工廠類,用于生成fallback類示例,通過這個屬性我們可以實現(xiàn)每個接口通用的容錯邏輯,減少重復的代碼path: 定義當前FeignClient的統(tǒng)一前綴,當我們項目中配置了server.context-path,server.servlet-path時使用
1.首先
我們在啟動類里面加入注解,聲明開啟Feign的遠程調(diào)用,如下:
@EnableEurekaClient
@SpringBootApplication
@EnableFeignClients
public class LoginStart {
?? ?public static void main(String[] args) {
?? ??? ?SpringApplication.run(LoginStart.class, args);
?? ?}
}2.編寫接口類
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.編寫熔斷類
發(fā)生錯誤時回調(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.然后我們準備兩個消費者工程
custorm(服務(wù)方),login(調(diào)用方),然后在login的controller中寫前臺調(diào)用接口:
@Autowired
private IRemoteCallService remot;
?? ?
@RequestMapping("/config")
public String config() {
?? ?String[] names = {"王五","張柳"};
?? ?return remot.test(names).toString();
}5.然后在custorm工程中寫一個接口
在這個接口里我們只將傳輸進來的數(shù)據(jù)再添加一個數(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.然后我們啟動注冊中心
配置中心以及兩個消費者服務(wù),需要了解配置中心和注冊中心的搭建可以看我前兩篇文章,啟動后瀏覽器我們進行訪問

可以看到,返回的數(shù)據(jù)中已經(jīng)包含了custorm工程中拼接的數(shù)據(jù),說明我們遠程調(diào)用接口成功,以上就是feign的簡單使用
另外補充一些面試中長問的如何給@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è)置多個屬性時,可以使用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.實現(xiàn)RequestInterceptor接口,如下:
@Configuration
public class FeignRequestInterceptor implements RequestInterceptor {
@Override
public void apply(RequestTemplate temp) {
temp.header(HttpHeaders.AUTHORIZATION, "XXXXX");
}
}以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
- springcloud-feign調(diào)用報錯問題
- 如何解決使用restTemplate進行feign調(diào)用new HttpEntity<>報錯問題
- 解決Spring調(diào)用Feign報錯:java.io.IOException:Incomplete output stream問題
- 通過FeignClient調(diào)用微服務(wù)提供的分頁對象IPage報錯的解決
- 使用feign發(fā)送http請求解析報錯的問題
- Springcloud?feign傳日期類型參數(shù)報錯的解決方案
- 解決配置Feign時報錯PathVariable annotation was empty on param 0.
相關(guān)文章
Java的分支結(jié)構(gòu)與循環(huán)你知道多少
這篇文章主要為大家詳細介紹了Java的分支結(jié)構(gòu)與循環(huán),文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助2022-02-02
通過xml配置SpringMVC注解DispatcherServlet初始化過程解析
這篇文章主要為大家介紹了通過xml配置SpringMVC注解DispatcherServlet初始化過程解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-10-10
java web SpringMVC后端傳json數(shù)據(jù)到前端頁面實例代碼
本篇文章主要介紹了java web SpringMVC后端傳json數(shù)據(jù)到前端頁面實例代碼,具有一定的參考價值,感興趣的小伙伴們可以參考一下。2017-03-03

