Spring Cloud中Feign的常见问题

流过昼夜 提交于 2019-11-28 23:08:59

一、FeignClient接口,不能使用@GettingMapping 之类的组合注解

@FeignClient("microservice-provider-user")
public interface UserFeignClient {
 @RequestMapping(value = "/simple/{id}", method = RequestMethod.GET)
 public User findById(@PathVariable("id") Long id);
 ...
}

这边的@RequestMapping(value = "/simple/{id}", method = RequestMethod.GET) 不能写成@GetMapping("/simple/{id}") 

二、FeignClient接口中,如果使用到@PathVariable ,必须指定其value

@FeignClient("microservice-provider-user")
public interface UserFeignClient {
 @RequestMapping(value = "/simple/{id}", method = RequestMethod.GET)
 public User findById(@PathVariable("id") Long id);
 ...
}

这边的@PathVariable("id") 中的”id”,不能省略,必须指定。

三、FeignClient多参数的构造

如果想要请求microservice-provider-user 服务,并且参数有多个例如:http://microservice-provider-user/query-by?id=1&username=张三 要怎么办呢?

直接使用复杂对象:

@FeignClient("microservice-provider-user")
public interface UserFeignClient {
 @RequestMapping(value = "/query-by", method = RequestMethod.GET)
 public User queryBy(User user);
 ...
}

该请求不会成功,只要参数是复杂对象,即使指定了是GET方法,feign依然会以POST方法进行发送请求。

正确的写法:

写法1:

@FeignClient("microservice-provider-user")
public interface UserFeignClient {
 @RequestMapping(value = "/query-by", method = RequestMethod.GET)
 public User queryBy(@RequestParam("id")Long id, @RequestParam("username")String username);
}

写法2:

@FeignClient(name = "microservice-provider-user")
public interface UserFeignClient {
 @RequestMapping(value = "/query-by", method = RequestMethod.GET)
 public List<User> queryBy(@RequestParam Map<String, Object> param);
}

四、Feign使用@FeignClient指定fallback无效

我们知道Feign本身就是支持Hystrix的,可以直接使用@FeignClient(value = "microservice-provider-user", fallback = XXX.class) 来指定fallback的类,这个fallback类集成@FeignClient所标注的接口即可。但是在实际项目中发现fallback没有效果。原来是我们需要开启Hystrix:

feign.hystrix.enabled=true

五、Feign如果想要使用Hystrix Stream,需要做一些额外操作

假设我们需要使用Hystrix Stream进行监控,默认情况下,访问http://IP:PORT/hystrix.stream 是个404。如何为Feign增加Hystrix Stream支持呢?

需要以下两步:

第一步:添加依赖,示例:

<!-- 整合hystrix,其实feign中自带了hystrix,引入该依赖主要是为了使用其中的hystrix-metrics-event-stream,用于dashboard -->
<dependency>
 <groupId>org.springframework.cloud</groupId>
 <artifactId>spring-cloud-starter-hystrix</artifactId>
</dependency>

第二步:在启动类上添加@EnableCircuitBreaker 注解

这样修改以后,访问任意的API后,再访问http://IP:PORT/hystrix.stream,就会展示出一大堆的API监控数据了。

六、如果需要自定义单个Feign配置,Feign的@Configuration 注解的类不能与@ComponentScan 的包重叠

如果包重叠,将会导致所有的Feign Client都会使用该配置。

七、@FeignClient 的属性注意点

(1) serviceId属性已经失效,尽量使用name属性。例如:@FeignClient(serviceId = "microservice-provider-user")这么写是不推荐的,应写为:@FeignClient(name = "microservice-provider-user")

(2) 在使用url属性时,在老版本的Spring Cloud中,不需要提供name属性,但是在新版本(例如Brixton、Camden)@FeignClient必须提供name属性,并且name、url属性支持占位符。例如:

@FeignClient(name = "${feign.name}", url = "${feign.url}")

八、首次请求失败
详见:解决Spring Cloud中Feign/Ribbon第一次请求失败的方法

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!