@FeignClient path属性路径前缀带路径变量
路过君_P 人气:0@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}")
@FeignClient使用详解
@FeignClient标签的常用属性如下
name
:指定FeignClient的名称,如果项目使用了Ribbon,name属性会作为微服务的名称,用于服务发现url
: url一般用于调试,可以手动指定@FeignClient调用的地址decode404
:当发生http 404错误时,如果该字段位true,会调用decoder进行解码,否则抛出FeignExceptionconfiguration
: Feign配置类,可以自定义Feign的Encoder、Decoder、LogLevel、Contractfallback
: 定义容错的处理类,当调用远程接口失败或超时时,会调用对应接口的容错逻辑,fallback指定的类必须实现@FeignClient标记的接口fallbackFactory
: 工厂类,用于生成fallback类示例,通过这个属性我们可以实现每个接口通用的容错逻辑,减少重复的代码path
: 定义当前FeignClient的统一前缀,当我们项目中配置了server.context-path,server.servlet-path时使用
1.首先
我们在启动类里面加入注解,声明开启Feign的远程调用,如下:
@EnableEurekaClient @SpringBootApplication @EnableFeignClients public class LoginStart { public static void main(String[] args) { SpringApplication.run(LoginStart.class, args); } }
2.编写接口类
value="/xxx/xxx"就是我们服务方暴露的接口地址,如下:
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.编写熔断类
发生错误时回调:
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("接口调用失败"); return null; } }
4.然后我们准备两个消费者工程
custorm(服务方),login(调用方),然后在login的controller中写前台调用接口:
@Autowired private IRemoteCallService remot; @RequestMapping("/config") public String config() { String[] names = {"王五","张柳"}; return remot.test(names).toString(); }
5.然后在custorm工程中写一个接口
在这个接口里我们只将传输进来的数据再添加一个数据返回回去
@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.然后我们启动注册中心
配置中心以及两个消费者服务,需要了解配置中心和注册中心的搭建可以看我前两篇文章,启动后浏览器我们进行访问
可以看到,返回的数据中已经包含了custorm工程中拼接的数据,说明我们远程调用接口成功,以上就是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.在方法参数前面添加@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); }
设置多个属性时,可以使用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.实现RequestInterceptor接口,如下:
@Configuration public class FeignRequestInterceptor implements RequestInterceptor { @Override public void apply(RequestTemplate temp) { temp.header(HttpHeaders.AUTHORIZATION, "XXXXX"); } }
以上为个人经验,希望能给大家一个参考,也希望大家多多支持。
加载全部内容