上一章中完成了Ribbon和hytrix的整合,本章整合Hystrix和Feign
要实现Hystrix和Feign的整合,需要在消费端完成以下几个步骤:
1.添加Hystrix和Feign的maven依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix</artifactId>
</dependency>
2.在启动类中添加注解
@EnableFeignClients
@EnableCircuitBreaker
3.添加FeignClient接口
package com.example.demo.feign;
@FeignClient(name="spring-cloud-provider",fallback=UserFeignClientFallback.class)
public interface UserFeignClient {
@RequestMapping(value="/user/get?id={id}",method=RequestMethod.GET)
public User get(@PathVariable("id") String id);
@RequestMapping(value="/user/list",method=RequestMethod.GET)
public List<User> list();
}
4.添加Fallback的实现了,Fallback实现了FeignClient接口
package com.example.demo.fallback;
@Component
public class UserFeignClientFallback implements UserFeignClient{
@Override
public User get(String id) {
// TODO Auto-generated method stub
return new User();
}
@Override
public List<User> list() {
// TODO Auto-generated method stub
return new ArrayList<User>();
}
}
5.使用FeignClient实现对微服务的调用
//只需要在使用的SpringBean中注入Feignclient即可
@Autowired
private UserFeignClient userFeignClient;
使用fallbackFactory实现Hystrix和Feign的整合,并且捕获异常
UserFeignClient.java
把@FeignClient的fallback属性给删除了,并且添加fallbackFactory=UserFeignClientFactory.class
package com.example.demo.feign;
@FeignClient(name="spring-cloud-provider"/*,fallback=UserFeignClientFallback.class*/,fallbackFactory=UserFeignClientFactory.class)
public interface UserFeignClient {
@RequestMapping(value="/user/get?id={id}",method=RequestMethod.GET)
public User get(@PathVariable("id") String id);
@RequestMapping(value="/user/list",method=RequestMethod.GET)
public List<User> list();
}
UserFeignClientFactory.java
package com.example.demo.fallback;
@Component
public class UserFeignClientFactory implements FallbackFactory<UserFeignClient>{
@Override
public UserFeignClient create(Throwable arg0) {
//返回一个匿名内部类,这个匿名内部类实现了FeignClient接口
return new UserFeignClient(){
@Override
public User get(String id) {
// TODO Auto-generated method stub
return new User("-1", "error", -1, new Date());
}
@Override
public List<User> list() {
// TODO Auto-generated method stub
return new ArrayList<User>();
}};
}
}
验证
关闭微服务,浏览器打开http://192.168.88.101:9000/user/feign_get?id=1,在消费端被浏览器调用的时候
浏览器显示如下内容:
{"id":"-1","userName":"error","age":-1,"birthday":1503539977737}
系统抛出下面的异常
java.lang.RuntimeException: com.netflix.client.ClientException: Load balancer does not have available server for client: spring-cloud-provider
at org.springframework.cloud.netflix.feign.ribbon.LoadBalancerFeignClient.execute(LoadBalancerFeignClient.java:71)
at feign.SynchronousMethodHandler.executeAndDecode(SynchronousMethodHandler.java:97)
at feign.SynchronousMethodHandler.invoke(SynchronousMethodHandler.java:76)
at feign.hystrix.HystrixInvocationHandler$1.run(HystrixInvocationHandler.java:108)