Feign使用Hystrix(断路器的使用)
作者:互联网
前言
在springcloud中,为Feign添加回退更加简单。事实上,springcloud默认已为Feign整合了Hystrix,要想为Feign打开Hystrix支持,只需要设置feign.hystrix.enabled=true即可。
编码
1.复制项目microservie-consumer-movie-feign,将ArtifactId修改为microservice-consumer-movie-feign-hystrix-fallback.
2.在application.yml中添加feign.hystrix.enabled: true,从而开启Feign的Hystrix支持。
server: port: 8082 eureka: client: serviceUrl: defaultZone: http://localhost:8083/eureka/ instance: prefer-ip-address: true spring: application: name: microservice-consumer-movie feign: hystrix: enabled: true
3.将之前编写的Feign接口修改成如下内容:
@FeignClient(name = "microservice-provider-user",fallback = FeignClientFallback.class) public interface UserFeignClient { @RequestMapping(value="/{id}",method = RequestMethod.GET) public User findById(@PathVariable("id") Long id); } @Component class FeignClientFallback implements UserFeignClient{ public User findById(Long id) { User user = new User(); user.setId(-1L); user.setUsername("默认用户"); return user; } }
由代码可知,只需使用@FeignClient注解的fallback属性,就可为指定名称的Feign客户添加回退。
测试
启动microservice-discovery-eureka.
启动microservice-provider-user.
启动microservice-consumer-movie-feign-hystrix-fallback.
访问http://localhost:8082/user/1,可正常获得结果。
{"id":1,"username":"account1","name":"张三","age":20,"balance":98.23}
停止microservice-provider-user.
再次访问http://localhost:8082/user/1,可获得如下结果。说明当用户微服务不可用时,进入了回退的逻辑。
{"id":-1,"username":"默认用户","name":null,"age":null,"balance":null}
补充:在springcloud Dalston之前的版本中,Feign默认开启Hystrix支持,无需设置feign.hystrix.enabled=true.从springcloud Dalston版本开始,Feign的Hystrix支持默认关闭,需要手动设置开启。
由于代码过于简单,这里就不提交源码了
标签:feign,Hystrix,Feign,断路器,user,microservice,id 来源: https://blog.csdn.net/Dingwensheng1222/article/details/97282896