概念
整体资源快不够了,忍痛将某些服务先关掉,待渡过难关,再开启回来。
服务降级处理是在客户端完成,与服务端无关
所有的RESTful风格的接口都需要做服务降级的处理
这样就带来了一些问题,分析:
1.使用@HystrixCommand带来的异常通知方法,这导致有多少个方法就要写多少个异常通知方法,方法膨胀
2.业务代码出现其他方法,耦合度增强
为了降低耦合度同时也为了代码的可读性,使用Hystrix的FallbackFactory返回通知
服务降级
所谓降级,一般是从整体负荷考虑的,当某个服务熔断后,服务器将不再被调用
此时客户端可以准备一个fallback回调,返回一个缺省值
这样所,服务可用,比起全部服务直接挂掉要好
使用
1.修改api工程
在com.yan.cloudapi.service包下新建实现了FallbackFactory的接口,实现功能接口是DeptClientService
并在该类添加注解
@Component//不要忘记添加,不要忘记添加
package com.yan.cloudapi.service;
import com.yan.cloudapi.pojo.Dept;
import feign.hystrix.FallbackFactory;
import org.springframework.stereotype.Component;
import java.util.List;
/**
* @Author: 闫明辉
* @Description:
* @Date: Create in 12:45 2020/3/9
*/
@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,fallback通知指定写好的类
package com.yan.cloudapi.service;
import com.yan.cloudapi.pojo.Dept;
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 java.util.List;
/**
* @Author: 闫明辉
* @Description:
* @Date: Create in 15:25 2020/3/6
*/
@FeignClient(value = "democloud-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.demo-consumer-dept-fegin工程的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/
至此,修改完成
测试
1.启动eureka集群7001、7002、7003
2.启动demo-provider-dept-8001
3.启动demo-consumer-dept-fegin
4.测试集群 localhost:7001、ocalhost:7002、ocalhost:7003
红色部分为eureka的自我保护
5.测试接口 http://localhost/consumer/dept/get/2
6.模拟服务压力过大,暂时关闭服务器,继续调用接口 http://localhost/consumer/dept/get/2
提示出现,完成!
参考资料:尚硅谷周阳Spring Cloud讲解