SpringCloud学习系列-Hystrix断路器(3)
服务降级
1.是什么
整体资源快不够了,忍痛将某些服务先关掉,待渡过难关,再开启回来。
服务降级处理是在客户端实现完成的,与服务端没有关系
2.实验代码
1.修改microservicecloud-api工程,
根据已经有的DeptClientService接口新建一个实现了
FallbackFactory接口的类DeptClientServiceFallbackFactory
package com.atguigu.springcloud.service; import java.util.List; import org.springframework.stereotype.Component; import com.atguigu.springcloud.entities.Dept; import feign.hystrix.FallbackFactory; @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; } }; } }
千万不要忘记在类上面新增@Component注解,大坑!!!
2.修改microservicecloud-api工程,DeptClientService接口在注解@FeignClient中添加fallbackFactory属性值
package com.atguigu.springcloud.service; import java.util.List; import org.springframework.cloud.netflix.feign.FeignClient; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import com.atguigu.springcloud.entities.Dept; @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); }
3.microservicecloud-api工程 mvn clean install
4.microservicecloud-consumer-dept-feign工程修改YML
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/
3.测试
3个eureka先启动
微服务microservicecloud-provider-dept-8001启动
microservicecloud-consumer-dept-feign启动
正常访问测试:http://localhost/consumer/dept/get/1
故意关闭微服务microservicecloud-provider-dept-8001
客户端自己调用提示:
http://localhost/consumer/dept/get/1
此时服务端provider已经down了,但是我们做了服务降级处理,让客户端在服务端不可用时也会获得提示信息而不会挂起耗死服务器