搭建hystrix服务治理

hystrix中文名豪猪,浑身是刺,用于自我保护,用豪猪命名也寓意着服务治理的安全性,hystrix可以用来做微服务的降级,熔断,限流等。

 

下面介绍springcloud服务下如何搭建hystrix服务

 

1.pom.xml添加引用

 

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netfix-hystrix</artifactId>
</dependency>

2.新增config.properties配置文件,和application.properties文件同级,内容如下:

 

# Hystrix 全局配置
# Hystrix 默认加载的配置文件 - 限流、 熔断示例

# 线程池大小
hystrix.threadpool.default.coreSize=1
# 缓冲区大小, 如果为-1,则不缓冲,直接进行降级 fallback
hystrix.threadpool.default.maxQueueSize=200
# 缓冲区大小超限的阈值,超限就直接降级,即使maxQueueSize没有达到,达到queueSizeRejectionThreshold该值后,请求也会被拒绝
hystrix.threadpool.default.queueSizeRejectionThreshold=2

# 执行策略
# 资源隔离模式,默认thread。 还有一种叫信号量semaphore
hystrix.command.default.execution.isolation.strategy=THREAD
# 是否打开超时
hystrix.command.default.execution.timeout.enabled=true
# 超时时间,默认1000毫秒
hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds=1000
# 超时时中断线程
hystrix.command.default.execution.isolation.thread.interruptOnTimeout=true
# 取消时候中断线程
hystrix.command.default.execution.isolation.thread.interruptOnFutureCancel=false
# 信号量模式下,最大并发量
hystrix.command.default.execution.isolation.semaphore.maxConcurrentRequests=2

# 降级策略
# 是否开启服务降级,如果开启,执行失败或者超时时会执行fallback
hystrix.command.default.fallback.enabled=true
# fallback执行并发量,如果超过这个值,抛出异常且fallback不会被调用
hystrix.command.default.fallback.isolation.semaphore.maxConcurrentRequests=100

# 熔断策略
# 启用/禁用熔断机制
hystrix.command.default.circuitBreaker.enabled=true
# 强制开启熔断,如果打开这个开关,所有请求都fallback
hystrix.command.default.circuitBreaker.forceOpen=false
# 强制关闭熔断,如果打开这个开关,即所有的短路都失效
hystrix.command.default.circuitBreaker.forceClosed=false
# 前提条件,一定时间内发起一定数量的请求。  也就是5秒钟内(这个5秒对应下面的滚动窗口长度)至少请求4次,熔断器才发挥起作用。  默认20
hystrix.command.default.circuitBreaker.requestVolumeThreshold=4
# 错误百分比。达到或超过这个百分比,熔断器打开。  比如:5秒内有4个请求,2个请求超时或者失败,就会自动开启熔断
hystrix.command.default.circuitBreaker.errorThresholdPercentage=50
# 10内熔断短路,10秒后,进入半打开状态(熔断开启,间隔一段时间后,会让一部分的命令去请求服务提供者,如果结果依旧是失败,则又会进入熔断状态,如果成功,就关闭熔断)。 默认5秒
hystrix.command.default.circuitBreaker.sleepWindowInMilliseconds=10000


#数据统计,收集
# 度量策略
# 5秒为一次统计周期,术语描述:滚动窗口的长度为5秒
# 设置统计的时间窗口值的,毫秒值,circuit break 的打开会根据1个rolling window的统计来计算。若rolling window被设为10000毫秒,则rolling window会被分成n个buckets,每个bucket包含success,failure,timeout,rejection的次数的统计信息。默认10000
hystrix.command.default.metrics.rollingStats.timeInMilliseconds=5000
# 统计周期内 度量桶的数量,必须被timeInMilliseconds整除。作用:
hystrix.command.default.metrics.rollingStats.numBuckets=10
# 是否收集执行时间,并计算各个时间段的百分比
hystrix.command.default.metrics.rollingPercentile.enabled=true
# 设置执行时间统计周期为多久,用来计算百分比
hystrix.command.default.metrics.rollingPercentile.timeInMilliseconds=60000
# 执行时间统计周期内,度量桶的数量
hystrix.command.default.metrics.rollingPercentile.numBuckets=6
# 执行时间统计周期内,每个度量桶最多统计多少条记录。设置为50,有100次请求,则只会统计最近的10次
hystrix.command.default.metrics.rollingPercentile.bucketSize=100
# 数据取样时间间隔
hystrix.command.default.metrics.healthSnapshot.intervalInMilliseconds=500

# 设置是否缓存请求,request-scope内缓存
hystrix.command.default.requestCache.enabled=false
# 设置HystrixCommand执行和事件是否打印到HystrixRequestLog中
hystrix.command.default.requestLog.enabled=false



# 限流策略

#如果没有定义HystrixThreadPoolKey,HystrixThreadPoolKey会默认定义为HystrixCommandGroupKey的值
hystrix.threadpool.userGroup.coreSize=1
hystrix.threadpool.userGroup.maxQueueSize=-1
hystrix.threadpool.userGroup.queueSizeRejectionThreshold=800


hystrix.threadpool.userThreadPool.coreSize=1
hystrix.threadpool.userThreadPool.maxQueueSize=-1
hystrix.threadpool.userThreadPool.queueSizeRejectionThreshold=800
hystrix.command.userCommandKey.execution.isolation.thread.timeoutInMilliseconds=5000

3.在application类中开启hystrix配置,如下所示:

package com.hewow.serveruser;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.hystrix.EnableHystrix;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@EnableEurekaClient
@SpringBootApplication
@EnableSwagger2
@EnableHystrix
public class ServerUserApplication {

    @Bean //注入restTemplate
    @LoadBalanced //在注册中心里进行查找微服务,Ribbon负载均衡
    //生成一个RestTemplate实例对象
    //使用user服务调用order服务就是通过这个restTemplate对象实现的
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }


    public static void main(String[] args) {
        SpringApplication.run(ServerUserApplication.class, args);
    }

}

 

 

4.在调用指定的方法服务上添加注解,指定hystrix策略

@GetMapping("getUserOrder")
@ApiOperation("获取用户订单信息")
@HystrixCommand(fallbackMethod = "getUserOrderFail")//发生异常的时候,会调用这个fallbackmethod方法,去处理
public String getUserOrder(){
    String url="http://service-order/getOrder";
    //返回值类型和我们的业务返回值一致
    return restTemplate.getForObject(url, String.class);
}

public String getUserOrderFail(){
    return "fail--001";
}

 

其中注解@HystrixCommand即添加服务治理,fallbackMethod指定服务超时或者失败后的调用方法。

5.测试,我们可以在http://service-order/getOrder这个服务里,sleep(2000)或者直接throw RuntimeException 来模拟服务超时或者失败,看看getUserOrder方法是不是调用了fallback指定的getUserOrderFail方法来验证配置成功与否。

6.备注

a) hystrix启动的时候会默认加载config.properties配置文件的信息;

b) hystrix配置文件详解请参考config.properties文件;

c) hystrix熔断和降级是在调用服务端做的,限流可以在调用服务端做也可以在服务提供端做;

d) 降级和熔断的区别是,第一次请求他会试着去调用远程服务,如果失败再调用fallback方法(降级);第二次请求还是会调用远程服务,如果失败再调用fallback方法(降级);这时hystrix认为远程服务不可用,暂时熔断这个服务;第三次请求时,hystrix发现这个服务在熔断列表中,直接调用fallback方法,而没有尝试去调用远程服务的过程,即是熔断;