SpringCloud07-Hystrix

SpringCloud07-Hystrix

1.Hystrix

  1. 多个微服务之间调用的时候,假设微服务A调用微服务B和微服务C,微服务B和微服务C又调用其它的微服务,这就是所谓的“扇出”。如果扇出的链路上某个微服务的调用响应时间过长或者不可用,对微服务A的调用就会占用越来越多的系统资源,进而引起系统崩溃,所谓的“雪崩效应”。

  2. Hystrix是一个用于处理分布式系统的延迟和容错的开源库,在分布式系统里,许多依赖不可避免的会调用失败,比如超时、异常等,Hystrix能够保证在一个依赖出问题的情况下,不会导致整体服务失败,避免级联故障,以提高分布式系统的弹性。

  3. Hystrix的功能。服务降级、服务熔断、服务监控、服务隔离。

2.创建微服务cloud-eureka-hystrix-open-feign-consumer-order80

  1. pom.xml
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
    <version>2.2.9.RELEASE</version>
</dependency>
  1. Main
//@EnableCircuitBreaker 注解过时,可以使用@EnableHystrix
@EnableHystrix
@EnableFeignClients
@EnableEurekaClient
@SpringBootApplication
public class CloudEurekaHystrixOpenFeignConsumerOrder80Main {

    public static void main(String[] args) {
        SpringApplication.run(CloudEurekaHystrixOpenFeignConsumerOrder80Main.class, args);
    }
}
  1. controller,服务降级主要代码。
@Slf4j
@RestController
public class PaymentController {

    @Resource
    private PaymentService paymentService;

    @GetMapping(value = "/consumer/hystrix/{id}")
    @HystrixCommand(fallbackMethod = "fallback", commandProperties = {
            // 当前方式执行超过1500,就返回服务降级 fallback的执行结果
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "1500")
    })
    public String hystrix(@PathVariable Integer id) throws InterruptedException {
        //int a = 10 / id;
        String hystrix = paymentService.hystrix(id);
        return hystrix;
    }

    public String fallback(@PathVariable Integer id) {
        return Thread.currentThread().getId() + "==============consumer" + id;
    }
}

3.Hystrix全局服务降级

@Slf4j
@RestController
@DefaultProperties(defaultFallback = "globalFallback")
public class PaymentController {

    @Resource
    private PaymentService paymentService;

    @GetMapping(value = "/consumer/hystrix/{id}")
    @HystrixCommand
    public String hystrix(@PathVariable Integer id) throws InterruptedException {
        //int a = 10 / id;
        String hystrix = paymentService.hystrix(id);
        return hystrix;
    }

    public String globalFallback() {
        return Thread.currentThread().getId() + "globalFallback==============" + 12;
    }
}

4.通过OpenFeign将降级方法和controller分类

  1. pom.xml依赖
<!--openfeign-->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<!--hystrix-->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
    <version>2.2.9.RELEASE</version>
</dependency>
  1. yml
# 新版中 feign: hystrix: enabled: true无法使用。
# 开启Feign对Hystrix的支持。
feign:
  circuitbreaker:
    enabled: true
  1. main
//@EnableCircuitBreaker 注解过时,可以使用@EnableHystrix
@EnableHystrix
@EnableFeignClients
@EnableEurekaClient
@SpringBootApplication
public class CloudEurekaHystrixOpenFeignConsumerOrder80Main {

    public static void main(String[] args) {
        SpringApplication.run(CloudEurekaHystrixOpenFeignConsumerOrder80Main.class, args);
    }
}
  1. controller
@Slf4j
@RestController
public class PaymentController {
    
	/**
     * 当使用OpenFeign定义Hystrix的降级方式时,Spring容器中会有两个PaymentService的实现类。
     * 一个是OpenFeign通过动态代理为PaymentService接口实现的远程调用的实例。
     * 另一个是fallback返回方法的实现类。
     *
     * 所以这里PaymentService的属性名称需要为paymentService,和PaymentService保持一致。
     * 需要确保注入的是OpenFeign动态代理的实例。
     * 否则注入fallback的实例,没有进行远程调用,直接返回fallback方法。
     */
    @Resource
    private PaymentService paymentService;

    @GetMapping(value = "/consumer/payment/ok/{id}")
    public String ok(@PathVariable int id) {
        String s = paymentService.ok(id);
        log.info("=={}", s);
        return s;
    }
}
  1. service
@FeignClient(value = "cloud-hystrix-provider-payment", fallback = PaymentServiceImpl.class)
public interface PaymentService {

    @GetMapping(value = "/payment/ok/{id}")
    String ok(@PathVariable("id") int id);
}

@Slf4j
@Component
public class PaymentServiceImpl implements PaymentService {

    @Override
    public String ok(int id) {
        log.info("=====================");
        return "ok , PaymentServiceImpl" + id;
    }
}

5.Hystrix服务熔断

  1. 熔断机制是应对雪崩效应的一种微服务链路保护机制。当扇出链路的某个微服务出错不可用或者响应时间太长时,会进行服务的降级,进而熔断该节点微服务的调用,快速返回错误的响应信息。当检测到该节点微服务调用响应正常后,恢复调用链路。

  2. 服务熔断的代码。

// 服务熔断
// 10次请求,60%失败,断路器打开。10秒后半开,重试,放行一个请求,成功 断路器关闭。否则10秒后继续重试。
@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"),// 失败率达到多少后跳闸
})
@GetMapping("/payment/circuit/{id}")
public String paymentCircuitBreaker(@PathVariable("id") Integer id) {
    if(id < 0) {
        throw new RuntimeException("id not 负数");
    }
    String serialNumber = IdUtil.simpleUUID();

    return Thread.currentThread().getName()+"\t"+"调用成功,流水号: " + serialNumber;
}

public String paymentCircuitBreaker_fallback(Integer id) {
    return "id is not true number, id: " +id;
}
  1. 5.2服务熔断代码说明。
    1. 默认情况下,熔断器处于关开状态,10秒中,超过10次请求,10(默认20次)次请求有60%(默认50%)失败,则打开熔断器,进行服务降级。
    2. 熔断器打开时不主提供服务,只返回fallback方法。
    3. 10000=10(默认5秒)秒后短路器处于半闭状态,放行一请求,这个请求执行完成,短路器就关闭。否则在过10秒,睡眠10秒,继续放行一个请求,继续重试。
  2. Hystrix熔断器默认配置。10秒中,超过20次请求,50%失败,打开熔断器,5秒熔断器进入到半开状态。
  3. 服务熔断配置类。HystrixCommandProperties
  4. Hystrix执行流程图。

image

6.Hystrix图形化界面搭建-Hystrix Dashboard

  1. 创建微服务cloud-consumer-hystrix-dashboard9001,用来监控cloud-eureka-hystrix-provider-payment8001服务提供者。
  2. pom.xml
<dependencies>
    <!-- Hystrix图形化界面 -->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-hystrix-dashboard</artifactId>
        <version>2.2.9.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <scope>runtime</scope>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>
  1. yml
server:
  port: 9001

# Hystrix Dashboard访问后出现Unable to connect to Command Metric Stream.错误
# 新版本需要在dashboard中配置代理。
hystrix:
  dashboard:
  	# 这里的配置和Hystrix Dashboard页面添加的连接保持一致。
    # 如果页面添加链接为http://127.0.0.1:8001/hystrix.stream,这里就配置127.0.0.1。
    # 如果页面添加连接为http://localhost:8001/hystrix.stream,这里就配置localhost。
    proxy-stream-allow-list:
      - 127.0.0.1
  1. Main
@SpringBootApplication
@EnableHystrixDashboard
public class CloudConsumerHystrixDashboard9001Main {

    public static void main(String[] args) {
        SpringApplication.run(CloudConsumerHystrixDashboard9001Main.class, args);
    }
}
  1. 在Hystrix Dashboard页面添加链接后出现Failed opening connection to http://localhost:8001/hystrix.stream?delay=100 : 404 : HTTP/1.1 404的解决方法
// 在cloud-eureka-hystrix-provider-payment8001,
// 即要使用Hystrix Dashboard监控的微服务中添加如下代码。

@EnableEurekaClient
@SpringBootApplication
@EnableHystrix
public class CloudEurekaHystrixProviderPayment8001Main {

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

    /**
     *此配置是为了服务监控而配置,与服务容错本身无关,springcloud升级后的坑
     *ServletRegistrationBean因为springboot的默认路径不是"/hystrix.stream",
     *只要在自己的项目里配置上下面的servlet就可以了
     *否则,Unable to connect to Command Metric Stream 404
     */
    @Bean
    public ServletRegistrationBean getServlet() {
        System.out.println("===========================");
        HystrixMetricsStreamServlet streamServlet = new HystrixMetricsStreamServlet();
        ServletRegistrationBean registrationBean = new ServletRegistrationBean(streamServlet);
        registrationBean.setLoadOnStartup(1);
        registrationBean.addUrlMappings("/hystrix.stream");
        registrationBean.setName("HystrixMetricsStreamServlet");
        return registrationBean;
    }
}

7.Hystrix服务容器其他配置

@HystrixCommand(fallbackMethod = "fallbackMethod",
                groupKey = "strGroupCommand",
                commandKey = "strCommand",
                threadPoolKey = "strThreadPool",

                commandProperties = {
                    // 设置隔离策略,THREAD 表示线程池 SEMAPHORE:信号池隔离
                    @HystrixProperty(name = "execution.isolation.strategy", value = "THREAD"),
                    // 当隔离策略选择信号池隔离的时候,用来设置信号池的大小(最大并发数)
                    @HystrixProperty(name = "execution.isolation.semaphore.maxConcurrentRequests", value = "10"),
                    // 配置命令执行的超时时间
                    @HystrixProperty(name = "execution.isolation.thread.timeoutinMilliseconds", value = "10"),
                    // 是否启用超时时间
                    @HystrixProperty(name = "execution.timeout.enabled", value = "true"),
                    // 执行超时的时候是否中断
                    @HystrixProperty(name = "execution.isolation.thread.interruptOnTimeout", value = "true"),
                    // 执行被取消的时候是否中断
                    @HystrixProperty(name = "execution.isolation.thread.interruptOnCancel", value = "true"),
                    // 允许回调方法执行的最大并发数
                    @HystrixProperty(name = "fallback.isolation.semaphore.maxConcurrentRequests", value = "10"),
                    // 服务降级是否启用,是否执行回调函数
                    @HystrixProperty(name = "fallback.enabled", value = "true"),
                    // 是否启用断路器
                    @HystrixProperty(name = "circuitBreaker.enabled", value = "true"),
                    // 该属性用来设置在滚动时间窗中,断路器熔断的最小请求数。例如,默认该值为 20 的时候,如果滚动时间窗(默认10秒)内仅收到了19个请求, 即使这19个请求都失败了,断路器也不会打开。
                    @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "20"),

                    // 该属性用来设置在滚动时间窗中,表示在滚动时间窗中,在请求数量超过 circuitBreaker.requestVolumeThreshold 的情况下,如果错误请求数的百分比超过50, 就把断路器设置为 "打开" 状态,否则就设置为 "关闭" 状态。
                    @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "50"),
                    // 该属性用来设置当断路器打开之后的休眠时间窗。 休眠时间窗结束之后,会将断路器置为 "半开" 状态,尝试熔断的请求命令,如果依然失败就将断路器继续设置为 "打开" 状态,如果成功就设置为 "关闭" 状态。
                    @HystrixProperty(name = "circuitBreaker.sleepWindowinMilliseconds", value = "5000"),
                    // 断路器强制打开
                    @HystrixProperty(name = "circuitBreaker.forceOpen", value = "false"),
                    // 断路器强制关闭
                    @HystrixProperty(name = "circuitBreaker.forceClosed", value = "false"),
                    // 滚动时间窗设置,该时间用于断路器判断健康度时需要收集信息的持续时间
                    @HystrixProperty(name = "metrics.rollingStats.timeinMilliseconds", value = "10000"),

                    // 该属性用来设置滚动时间窗统计指标信息时划分"桶"的数量,断路器在收集指标信息的时候会根据设置的时间窗长度拆分成多个 "桶" 来累计各度量值,每个"桶"记录了一段时间内的采集指标。
                    // 比如 10 秒内拆分成 10 个"桶"收集这样,所以 timeinMilliseconds 必须能被 numBuckets 整除。否则会抛异常
                    @HystrixProperty(name = "metrics.rollingStats.numBuckets", value = "10"),
                    // 该属性用来设置对命令执行的延迟是否使用百分位数来跟踪和计算。如果设置为 false, 那么所有的概要统计都将返回 -1。
                    @HystrixProperty(name = "metrics.rollingPercentile.enabled", value = "false"),
                    // 该属性用来设置百分位统计的滚动窗口的持续时间,单位为毫秒。
                    @HystrixProperty(name = "metrics.rollingPercentile.timeInMilliseconds", value = "60000"),
                    // 该属性用来设置百分位统计滚动窗口中使用 “ 桶 ”的数量。
                    @HystrixProperty(name = "metrics.rollingPercentile.numBuckets", value = "60000"),
                    // 该属性用来设置在执行过程中每个 “桶” 中保留的最大执行次数。如果在滚动时间窗内发生超过该设定值的执行次数,
                    // 就从最初的位置开始重写。例如,将该值设置为100, 滚动窗口为10秒,若在10秒内一个 “桶 ”中发生了500次执行,
                    // 那么该 “桶” 中只保留 最后的100次执行的统计。另外,增加该值的大小将会增加内存量的消耗,并增加排序百分位数所需的计算时间。
                    @HystrixProperty(name = "metrics.rollingPercentile.bucketSize", value = "100"),

                    // 该属性用来设置采集影响断路器状态的健康快照(请求的成功、 错误百分比)的间隔等待时间。
                    @HystrixProperty(name = "metrics.healthSnapshot.intervalinMilliseconds", value = "500"),
                    // 是否开启请求缓存
                    @HystrixProperty(name = "requestCache.enabled", value = "true"),
                    // HystrixCommand的执行和事件是否打印日志到 HystrixRequestLog 中
                    @HystrixProperty(name = "requestLog.enabled", value = "true"),

                },
                threadPoolProperties = {
                    // 该参数用来设置执行命令线程池的核心线程数,该值也就是命令执行的最大并发量
                    @HystrixProperty(name = "coreSize", value = "10"),
                    // 该参数用来设置线程池的最大队列大小。当设置为 -1 时,线程池将使用 SynchronousQueue 实现的队列,否则将使用 LinkedBlockingQueue 实现的队列。
                    @HystrixProperty(name = "maxQueueSize", value = "-1"),
                    // 该参数用来为队列设置拒绝阈值。 通过该参数, 即使队列没有达到最大值也能拒绝请求。
                    // 该参数主要是对 LinkedBlockingQueue 队列的补充,因为 LinkedBlockingQueue 队列不能动态修改它的对象大小,而通过该属性就可以调整拒绝请求的队列大小了。
                    @HystrixProperty(name = "queueSizeRejectionThreshold", value = "5"),
                }
               )
public String doSomething() {
    //...
    return null;
}
posted @ 2021-10-07 19:56  行稳致远方  阅读(35)  评论(0)    收藏  举报