服务降级
整体资源快不够了,忍痛将某些服务先关掉,待渡过难关,再开启回来。
修改microservicecloud-api工程,
根据已经有的DeptClientService接口新建一个实现了
FallbackFactory接口的类DeptClientServiceFallbackFactory
@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;
}
};
}
}
修改microservicecloud-api工程,DeptClientService接口在注解@FeignClient中添加fallbackFactory属性值:
//@FeignClient(value = "MICROSERVICECLOUD-DEPT")
@FeignClient(value = "MICROSERVICECLOUD-DEPT", fallbackFactory = DeptClientServiceFallbackFactory.class)
public interface DeptClientService {
@RequestMapping(value = "/dept/get/{id}", method = RequestMethod.GET)
Dept get(@PathVariable("id") long id);
@RequestMapping(value = "/dept/list", method = RequestMethod.GET)
List<Dept> list();
@RequestMapping(value = "/dept/add", method = RequestMethod.POST)
boolean add(Dept dept);
}
microservicecloud-consumer-dept-feign工程修改YML
server:
port: 80
feign:
hystrix:
enabled: true # 开启feign对熔断的支持
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个eureka先启动
- 微服务microservicecloud-provider-dept-8001启动
- microservicecloud-consumer-dept-feign启动
访问http://localhost/consumer/dept/get/1:
关闭microservicecloud-provider-dept-8001,再次访问:
此时服务端provider已经down了,但是我们做了服务降级处理,让客户端在服务端不可用时也会获得提示信息而不会挂起耗死服务器