这是我参与8月更文挑战的第28天,活动详情查看:8月更文挑战
基本概念
Hystrix可以在SpringCloud结构中作用服务的断融,也就是在出错的时候的应急处理系统。在官网上是如下解释:Hystrix是Netflix开源的一款容错系统,能帮助使用者码出具备强大的容错能力和鲁棒性的程序。
Class单例Maven引用
<dependency>
<groupId>com.netflix.hystrix</groupId>
<artifactId>hystrix-core</artifactId>
<version>1.5.8</version>
</dependency>
如果要使用Hystrix,我们一般会继承HystrixCommand/HystrixObservableCommand然后我们将重新他的run()/construct()方法。
案列
public class MyHystrixCommand extends HystrixCommand {
private final String name;
public MyHystrixCommand(String name) {
super(HystrixCommandGroupKey.Factory.asKey("Example"));
this.name = name;
}
@Override
protected String run() {
return "Hello " + name;
}
}
以上是单列中Hystrix的实现,其实就是外加一个类来重构原先要执行的方法,重构后将在读取配置的方案,如:一个接口在访问的时候出错的概率有50%那么我们就视为这个服务是有问题的,这个时候熔断机制将接口返回我们所写的重构内容,给予用户友好的提示,并非服务器异常。
上述讲述的是单例,那么一下我们将写入到SpringCloud中,大家会更明白他的含义。
SpringCloud中Maven引用
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix-dashboard</artifactId>
</dependency>
这个是SpringCloud已经整合了Netflix的Hystrix,我们劲量用这个引用,之前说过SpringCloud是版本优先的,如果版本没有对应上,那么后续的开发我们将面临很多问题,那个时候再去修改架构那么是最痛苦的。
SpringCloud中的案列
yml中的配置
一下是有一个服务注册中心端口为7001(不知道的用户可以回头学习一下Eureka),端口80是Hystrix的服务
server:
port: 80
eureka:
client:
register-with-eureka: false #true 表示向注册中心注册自己 默认true
#fetch-registry: true #true 表示我自己是维护服务实例,并需要检索自己(当前服务) 默认true
service-url:
defaultZone: http://localhost:7001/eureka #入住地址
feign:
hystrix:
enabled: true
业务代码paymentCircuitBreaker
一下是熔断的业务,我们使用注解的形式将访问paymentCircuitBreaker``的错误信息和熔断规则赋予给paymentCircuitBreaker_fallback在服务出错的时候我们将返回paymentCircuitBreaker_fallback中的内容。是不是很简单呀~
/*--------------------------------------------- 服务熔断 ---------------------------------------------------*/
@HystrixCommand(fallbackMethod = "paymentCircuitBreaker_fallback" ,commandProperties = {
@HystrixProperty(name = "circuitBreaker.enabled",value = "true"),//是否开始断路器
@HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "10"),//请求次数
@HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "10000"),//时间窗口期
@HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "60"),//失败率达到多少后跳闸
})
public String paymentCircuitBreaker(@PathVariable("id") Integer id){
if(id < 0){
throw new RuntimeException("*******8 ID 不能为负数");
}
String serialNumber = IdUtil.simpleUUID();
return Thread.currentThread().getName()+"\t调用成功,流水号:"+serialNumber;
}
public String paymentCircuitBreaker_fallback(@PathVariable("id") Integer id){
return "id 不能为负数,请稍后再试, id:"+id;
}
以上的内容中,可以看到我们在HystrixCommand注解中配置了很多的HystrixProperty属性,一下我们讲一下他的所有属性内容。
HystrixProperty中的属性
/**
* HystrixCommandProperties
*/
// 统计滚动的时间窗口,默认:5000毫秒(取自circuitBreakerSleepWindowInMilliseconds)
private final HystrixProperty metricsRollingStatisticalWindowInMilliseconds;
// 统计窗口的Buckets的数量,默认:10个,每秒一个Buckets统计
private final HystrixProperty metricsRollingStatisticalWindowBuckets; // number of buckets in the statisticalWindow
// 是否开启监控统计功能,默认:true
private final HystrixProperty metricsRollingPercentileEnabled;
/* --------------熔断器相关------------------*/
// 熔断器在整个统计时间内是否开启的阀值,默认20。也就是在metricsRollingStatisticalWindowInMilliseconds(默认10s)内至少请求20次,熔断器才发挥起作用
private final HystrixProperty circuitBreakerRequestVolumeThreshold;
// 熔断时间窗口,默认:5秒.熔断器中断请求5秒后会进入半打开状态,放下一个请求进来重试,如果该请求成功就关闭熔断器,否则继续等待一个熔断时间窗口
private final HystrixProperty circuitBreakerSleepWindowInMilliseconds;
//是否启用熔断器,默认true. 启动
private final HystrixProperty circuitBreakerEnabled;
//默认:50%。当出错率超过50%后熔断器启动
private final HystrixProperty circuitBreakerErrorThresholdPercentage;
//是否强制开启熔断器阻断所有请求,默认:false,不开启。置为true时,所有请求都将被拒绝,直接到fallback
private final HystrixProperty circuitBreakerForceOpen;
//是否允许熔断器忽略错误,默认false, 不开启
private final HystrixProperty circuitBreakerForceClosed;
/* --------------信号量相关------------------*/
//使用信号量隔离时,命令调用最大的并发数,默认:10
private final HystrixProperty executionIsolationSemaphoreMaxConcurrentRequests;
//使用信号量隔离时,命令fallback(降级)调用最大的并发数,默认:10
private final HystrixProperty fallbackIsolationSemaphoreMaxConcurrentRequests;
/* --------------其他------------------*/
//使用命令调用隔离方式,默认:采用线程隔离,ExecutionIsolationStrategy.THREAD
private final HystrixProperty executionIsolationStrategy;
//使用线程隔离时,调用超时时间,默认:1秒
private final HystrixProperty executionIsolationThreadTimeoutInMilliseconds;
//线程池的key,用于决定命令在哪个线程池执行
private final HystrixProperty executionIsolationThreadPoolKeyOverride;
//是否开启fallback降级策略 默认:true
private final HystrixProperty fallbackEnabled;
// 使用线程隔离时,是否对命令执行超时的线程调用中断(Thread.interrupt())操作.默认:true
private final HystrixProperty executionIsolationThreadInterruptOnTimeout;
// 是否开启请求日志,默认:true
private final HystrixProperty requestLogEnabled;
//是否开启请求缓存,默认:true
private final HystrixProperty requestCacheEnabled; // Whether request caching is enabled.
/**
* HystrixCollapserProperties
*/
//请求合并是允许的最大请求数,默认: Integer.MAX_VALUE
private final HystrixProperty maxRequestsInBatch;
//批处理过程中每个命令延迟的时间,默认:10毫秒
private final HystrixProperty timerDelayInMilliseconds;
//批处理过程中是否开启请求缓存,默认:开启
private final HystrixProperty requestCacheEnabled;
/**
* HystrixThreadPoolProperties
*/
/* 配置线程池大小,默认值10个 */
private final HystrixProperty corePoolSize;
/* 配置线程值等待队列长度,默认值:-1 建议值:-1表示不等待直接拒绝,测试表明线程池使用直接决绝策略+ 合适大小的非回缩线程池效率最高.所以不建议修改此值。 当使用非回缩线程池时,queueSizeRejectionThreshold,keepAliveTimeMinutes 参数无效 */
private final HystrixProperty maxQueueSize;