@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}")

posted on   路过君  阅读(189)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 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笔记 默认登陆页面源码

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示