- 当整个微服务架构整体的负载超出了预设的上限阈值或即将到来的流量预计将会超过预设的阈值时,为了保证重要或基本的服务能正常运行,我们可以将一些 不重要 或 不紧急 的服务或任务进行服务的 延迟使用 或 暂停使用
新建降级配置类DeptClientServiceFallBackFactory
实现FallbackFactory 接口 ,重写create方法,new一个Feign接口的实现对象
@Component
public class DeptClientServiceFallBackFactory implements FallbackFactory {
@Override
public DeptClientService create(Throwable throwable) {
return new DeptClientService() {
@Override
public Dept queryById(Long id) {
return new Dept().setDeptno(id)
.setDname("id=>"+id+"没有信息,这个服务已经关闭了")
.setDbSource("no data");
}
@Override
public List<Dept> queryAll() {
return null;
}
@Override
public int addDept(Dept dept) {
return 0;
}
};
}
}
在Feign接口中指定刚才的降级配置类DeptClientServiceFallBackFactory
//fallbackFactory指定降级配置类
@FeignClient(value = "SPRINGCLOUD-PROVIDER-DEPT",fallbackFactory = DeptClientServiceFallBackFactory.class)
public interface DeptClientService {
@GetMapping("/dept/{id}")
public Dept queryById(@PathVariable("id") Long id);
@GetMapping("/dept")
public List<Dept> queryAll();
@PostMapping("/dept")
public int addDept(Dept dept);
}
在Feign消费者中开启降级
# 开启降级feign.hystrix
feign:
hystrix:
enabled: true
测试
服务正常,放回正常数据
关闭服务,再次访问