整体资源快不够用,先将某些服务关掉,待整体恢复后,再开启回来,服务降级处理是在客户端实现完成的,与服务端没有关系。
1. 修改microservicecloud-api工程 根据已经有的DeptClientService接口新建一个实现了FallbackFactory接口的类DeptClientServiceFallbackFactory
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 @Component public class DeptClientServiceFallbackFactory implements FallbackFactory <DeptClientService > { @Override public DeptClientService create (Throwable throwable) { return new DeptClientService() { @Override public Dept get (long id) { return new Dept().setDeptno(id) .setDname("该ID:" + id + "没有没有对应的信息,Consumer客户端提供的降级信息,此刻服务Provider已经关闭" ) .setDb_source("no this database in MySQL" ); } @Override public List<Dept> list () { return null ; } @Override public boolean add (Dept dept) { return false ; } }; } }
2. 修改DeptClientService接口 在注解@FeignClient中添加fallbackFactory属性值
1 2 3 4 5 6 7 8 9 10 @FeignClient (value = "MICROSERVICECLOUD-DEPT" , fallbackFactory=DeptClientServiceFallbackFactory.class ) public interface DeptClientService { @RequestMapping (value = "/dept/get/{id}" , method = RequestMethod.GET) public Dept get (@PathVariable("id" ) long id) ; @RequestMapping (value = "/dept/list" , method = RequestMethod.GET) public List<Dept> list () ; @RequestMapping (value = "/dept/add" , method = RequestMethod.POST) public boolean add (Dept dept) ; }
重新编译microservicecloud-api工程
3. microservicecloud-consumer-dept-feign工程修改yml 1 2 3 4 5 6 7 8 9 10 11 server: port: 80 feign: hystrix: enabled: true eureka: client: register-with-eureka: false service-url: defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/,http://eureka7003.com:7003/eureka/
4. 验证 启动Eureka集群, 再将微服务microservicecloud-provider-dept-8001启动, 最后启动microservicecloud-consumer-dept-feign
1 2 3 4 5 6 curl http://localhost/consumer/dept/get/1 { "deptno": 1, "dname": "开发部", "db_source": "cloudDB01" }
故意关闭微服务microservicecloud-provider-dept-8001
1 2 3 4 5 6 curl http://localhost/consumer/dept/get/1 { "deptno": 1, "dname": "该ID:1没有没有对应的信息,Consumer客户端提供的降级信息,此刻服务Provider已经关闭", "db_source": "no this database in MySQL" }
此时服务端provider已经down了,但是我们做了服务降级处理,让客户端在服务端不可用时也会获得提示信息而不会挂起耗死服务器
资源获取 公众号回复 : Hystrix服务降级 获取本节代码
公众号回复 : SpringCloud思维导图
Tips 欢迎收藏和转发,感谢你的支持!(๑•̀ㅂ•́)و✧
欢迎关注我:后端小哥,专注后端开发,希望和你一起进步!