现象
FeignClient注解中使用path属性定义url前缀时,如果使用了路径变量,则会报错 例如
代码语言:javascript复制@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
代码语言:javascript复制@FeignClient(name = "user-api")
@RequestMapping("/api/user/{id}")