@FeignClient path属性路径前缀带路径变量时报错处理
现象
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}")
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 单元测试从入门到精通
2020-04-11 spring 启动时自动运行
2020-04-11 spring cloud oauth2授权服务 默认tokenService配置源码
2020-04-11 spring cloud 搭建oauth2授权服务 使用redis存储令牌
2020-04-11 spring cloud oauth2授权服务 clientDetails配置源码
2020-04-11 spring 验证框架
2020-04-11 IDEA 插件整理
2020-04-11 spring security笔记 默认登陆页面源码