一.基于Hystrix的服务降级(服务消费者端)
服务降级是当服务器压力剧增的情况下,根据当前业务情况及流量对一些服务和页面有策略的降级,以此释放服务器资源以保证核心任务的正常运行
1.导入依赖
<!--Hystrix依赖-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
<version>2.2.10.RELEASE</version>
</dependency>
2.编写FallBackFactory类,记得添加@Component注解将其注册成spring组件
@Component
public class DeptFallBackFactory implements FallbackFactory<FeignDeptClient> {//Feign配置接口作为泛型
@Override
public FeignDeptClient create(Throwable cause) {
//返回Feign配置接口
return new FeignDeptClient() {
@Override
public Dept queryByDeptNo(Long deptno) {
return new Dept()
.setDeptno(deptno)
.setDname("服务已降级-无法连接到数据库---@Hystrix")
.setDb_source("服务已降级-无法连接到数据库---@Hystrix");
}
@Override
public List<Dept> queryAll() {
Dept dept = new Dept()
.setDeptno((long) -1)
.setDname("服务已降级-无法连接到数据库---@Hystrix")
.setDb_source("服务已降级-无法连接到数据库---@Hystrix");
List<Dept> list = null;
list.add(dept);
return list;
}
@Override
public boolean addDept(Dept dept) {
return false;
}
@Override
public boolean updateDept(Dept dept) {
return false;
}
@Override
public boolean deleteDept(Long deptno) {
return false;
}
};
}
}
3.为@FeignClient注解配置参数
fallbackFactory = DeptFallBackFactory.class
运行测试
1.开启服务消费端和服务提供端,进行查询测试
查询服务可以正常运行
2.关闭服务提供端,模拟在服务高峰期为了给核心服务提供资源而关闭了次级服务
可以看到此时已经调用了降级服务,返回消息以通知用户
二.基于Hystrix的服务熔断(服务提供者端)
服务熔断是一种保险措施,当某服务出现不可用或响应超时的情况时,为了防止整个系统出现雪崩,暂时停止对该服务的调用
1.导入依赖
<!--Hystrix依赖-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
<version>2.2.10.RELEASE</version>
</dependency>
2.编写FallBackMethod用于错误请求提示(于Controller层中)
//错误请求提示
public Dept queryByNoHystrix(Long deptno) {
return new Dept()
.setDeptno((long) -1)
.setDname("错误请求--@Hystrix")
.setDb_source("错误请求--@Hystrix");
}
3. 为需要Hystrix熔断服务的Controller层方法添加@HystrixCommand注解,并为其配置参数
此处仅举一例
@GetMapping("/{deptno}")
@HystrixCommand(fallbackMethod = "queryHystrix",commandProperties = {
//circuitBreaker.enabled 是否开启熔断 默认为true
//circuitBreaker.forceOpen 强制开启熔断器 拒绝所有请求 默认为false
//circuitBreaker.forceClosed 强制关闭熔断器 此时忽略circuitBreaker.errorThresholdPercentage 默认为false
@HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "5"),//一定时间内触发熔断的最小请求次数 默认为20
@HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "50"),//触发熔断器的一定时间内的请求错误率 默认为50
@HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "10000")//熔断后关闭服务的时间 默认为5000毫秒
})
public Dept queryByDeptNo(@PathVariable("deptno") Long deptno) {
Dept dept = deptServiceImpl.queryByDeptNo(deptno);
//抛出错误 触发fallbackmethod
if (dept==null){
throw new RuntimeException("deptno="+deptno+" is not in database");
}
return dept;
}
运行测试
1.开启服务提供者端,进行查询测试
查询服务可以正常运行
2.进行多次错误请求
3.进行正确请求
可以看到,即使此刻进行的是正确请求,也无法得到正确的结果,因为此时服务已熔断,不进行请求接收
稍等片刻后,熔断器会尝试性地通过一个请求以判断服务是否恢复正常
在接收到正确请求后,熔断器判断该服务恢复正常,可正常使用(当然,若继续进行多次错误请求,则服务将再次熔断)