版本说明
先说下使用的spring cloud和spring boot的版本
Disable HystrixCommands For FeignClients By Default
https://github.com/spring-cloud/spring-cloud-netflix/issues/1277
新建子module
父工程microservice-spring-cloud右键新建Maven Module 命名为:micorservice-consumer-movie-feign-hystrix ,为了简单我们把micorservice-consumer-movie-feign的内容copy到该子模块,修改下application.yml中的spring.application.name即可。
application.yml中开启Hystrix
server: port: 7901 spring: application: name: micorservice-consumer-movie-feign-hystrix #eureka eureka: client: service-url: defaultZone: http://artisan:artisan123@localhost:8761/eureka instance: prefer-ip-address: true instance-id: ${spring.application.name}:${spring.application.instance_id:${server.port}} # Disable HystrixCommands For FeignClients By Default # https://github.com/spring-cloud/spring-cloud-netflix/issues/1277 feign: hystrix: enabled: true
如果是application.property ,请设置 feign.hystrix.enabled=true
修改Feign接口
使用fallback属性指定回退类
回退类 也需要实现上面的接口,同时需要标注@Component让其成为受spring管理的bean
测试
- 启动microservice-discovery-eureka,注册中心
- 启动micorservice-provider-user,服务提供者
- 启动micorservice-consumer-movie-feign-hystrix,服务消费者开启了Hystrix
访问http://localhost:8761/ 确认下服务已经注册成功。
访问 http://localhost:7901/movie/1
{"id":1,"username":"artisan1","name":"小工匠一","age":10,"balance":100.00}
功能正常,OK。
现在停掉micorservice-provider-user
访问 http://localhost:7901/movie/1 ,进入了回退方法
{"id":1,"username":"默认用户","name":null,"age":null,"balance":null}
再次启动 micorservice-provider-user
再次访问 http://localhost:7901/movie/1
{"id":1,"username":"artisan1","name":"小工匠一","age":10,"balance":100.00}
功能正常,OK。