前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >@FeignClient path属性路径前缀带路径变量时报错处理

@FeignClient path属性路径前缀带路径变量时报错处理

作者头像
路过君
发布2021-10-15 15:16:23
3.2K0
发布2021-10-15 15:16:23
举报
文章被收录于专栏:路过君BLOG from CSDN

现象

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属性值
代码语言:javascript
复制
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}的路径变量,会导致解析异常
代码语言:javascript
复制
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}")
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2021/04/19 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 现象
  • 源码分析
  • 解决办法
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档