spring cloud 之 Hystrix

文章介绍了如何在SpringCloud环境中利用Hystrix实现服务熔断和降级,包括Hystrix的工作原理和状态管理。通过示例展示了两种方式:一是集成OpenFeign并使用FeignFallback接口实现熔断;二是使用@HystrixCommand注解直接在调用方法上实现熔断。同时,文章提到了相关的配置参数和注解配置,以控制熔断行为。
摘要由CSDN通过智能技术生成

Hystrix概述

Hystrix是一个供分布式系统使用,提供延迟和容错功能,保证复杂的分布系统在面临不可避免的失败是时,仍具有弹性。

当服务器A调用服务器B时,如果服务器B宕机,则服务器A不去调用。当服务器B在时间范围内未响应,服务器A延迟时间等待服务器B的响应,在SpringCloud框架里熔断机制通过Hystrix实现。Hystrix会监控微服务间调用的状况,当失败的调用到一定阈值,缺省是5秒内20次调用失败就会启动熔断机制

Hystrix的概念

服务熔断的状态

Closed:关闭状态,所有请求都正常访问。

Open:打开状态,所有请求都会被降级。Hystix会对请求情况计数,当一定时间内失败请求百分比达到阈值,则触发熔断,断路器会完全打开。默认失败比例的阈值是50%,请求次数最少不低于20次。

Half Open:半开状态,open状态不是永久的,打开后会进入休眠时间(默认是5S)。随后断路器会自动进入半开状态。此时会释放部分请求通过,若这些请求都是健康的,则会完全关闭断路器,否则继续保持打开,再次进行休眠计时

继承openFeign方式实现熔断

这里的注册中心选用Nacos,openFeign

服务调用方搭建

引入依赖

<dependencies>
        <!--nacos客户端依赖-->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>
         <!--feign-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>
        <!--  feign性能优化 apache httpclient包 支持连接池 默认使用jdk urlConnection 不支持连接池-->
        <dependency>
            <groupId>io.github.openfeign</groupId>
            <artifactId>feign-httpclient</artifactId>
        </dependency>

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

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

配置文件

spring:
  application:
    name: cloud-feign-client
  cloud:
    nacos:
      discovery:
        server-addr: 127.0.0.1:8848
server:
  port: 9300
feign:
  httpclient:
    connection-timeout: 5000
  hystrix:
    enabled: true
hystrix:
  command:
    default:
      circuitBreaker:
        # 触发熔断的错误比例
        errorThresholdPercentage: 50
        # 熔断后的休眠时间,单位:毫秒,即熔断开启到正常访问服务的时间间隔
        sleepWindowMilliseconds: 100000
        # 触发熔断的最小请求次数
        requestVolumeThreshold: 2
      execution:
        timeout:
          enabled: true
        isolation:
          # 隔离策略:线程隔离
          strategy: THREAD
          thread:
            # 线程超时时间:调用Fallback
            timeoutInMilliseconds: 5000

这里使用第一种方式实现熔断,集成openFeign的接口,也就是FeignFallback 

package com.slbuildenv.cloud.client;

import com.slbuildenv.cloud.hysrix.FeignFallback;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;

@FeignClient(value="cloud-test-service" ,fallback = FeignFallback.class)
public interface TestFeign {

    @GetMapping("/find/date")
    String findDate();
}
package com.slbuildenv.cloud.hysrix;

import com.slbuildenv.cloud.client.TestFeign;
import org.springframework.stereotype.Component;

@Component
public class FeignFallback  implements TestFeign {

    @Override
    public String findDate() {
        System.out.println("服务熔断降级");
        return "服务熔断降级";
    }
}

 调用controller

package com.slbuildenv.cloud.controller;

import com.slbuildenv.cloud.client.TestFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/feign")
public class TestFeignRemote {

    @Autowired
    private TestFeign testFeign;

    @GetMapping("/date")
    public String getRemoteDate() throws InterruptedException {
       return  testFeign.findDate();
    }

}

被调用方搭建

配置文件就不列举啦,就是注册个nacos注册中心,依赖不需要Hystrix

package com.slbuildenv.cloud.controller;

import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@RestController
@RequestMapping("/find")
@RefreshScope
public class TestFeign {


    @GetMapping("/date")
    public String getDate(){
        return LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
    }
}

测试调用

不启动被调用方

注解方式实现熔断

启动类上加@EnableHystrix

package com.slbuildenv.cloud;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.hystrix.EnableHystrix;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.ComponentScan;

@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
@EnableHystrix
public class FeignMainApplication {
    public static void main(String[] args) {
        SpringApplication.run(FeignMainApplication.class,args);
    }
}

 调用方法添加@HystrixCommand方法

package com.slbuildenv.cloud.controller;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.slbuildenv.cloud.client.TestFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/feign")
public class TestFeignRemote {

    @Autowired
    private TestFeign testFeign;

    @GetMapping("/date")
    @HystrixCommand(fallbackMethod = "fallBack")
    public String getRemoteDate() throws InterruptedException {
       return  testFeign.findDate();
    }

    public String fallBack(){
        System.out.println("注解方式实现熔断");
        return "注解方式实现熔断";
    }
}

需要去掉继承接口的方式:

@FeignClient(value="cloud-test-service" ,fallback = FeignFallback.class)

改为:

@FeignClient(value="cloud-test-service")

如果不去掉,两者共存,则继承接口方式会覆盖注解方式实现,优先级较高

测试结果 

 其他注解配置

        // 当前隔离策略选择信号池隔离的时候,用来设置信号池的大小(最大并发数)
        @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的时候,如果滚动时间窗(默认10s)内仅收到了19个请求,即使这19个请求都失败了,断路器也不会打开。
        @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "20"),

        // 该属性用来设置在滚动时间窗中,表示在滚动时间窗中,在请求数量超过circuitBreaker.RequestVolumeThreshold的情况下,
        // 如果错误请求数的百分比超过50,就把断路器设置为“打开”状态,否则就设置为“关闭”状态。
        @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "10000"),//时间窗口期

        // 断路器强制打开
        @HystrixProperty(name = "circuitBreaker.forceOpen",value = "false"),

        // 断路器强制关闭
        @HystrixProperty(name = "circuitBreaker.forceClosed",value = "false"),

        // 滚动时间窗设置,该时间用于断路器判断健康度时需要收集信息的持续时间
        @HystrixProperty(name = "metrics.rollingStats.timeInMilliseconds",value = "10000"),

        // 该属性用来设置滚动时间窗统计指标信息时划分“桶”的数量,
        // 断路器在收集指标信息的时候会根据设置的时间窗长度拆分成多个“桶”来累计个度量值,每个“桶”记录了一段时间内的采集指标。
        // 比如10s内拆分成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,滚动窗口为10s,若在10s内一个“桶”中发生了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"),

        @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "60"),//失败率达到多少后跳闸
},threadPoolProperties = {

        // 该参数用来设置执行命令线程池的核心线程数,该值也就是命令执行的最大并发量
        @HystrixProperty(name = "coreSize",value = "10"),

        // 该参数用来设置线程池的最大队列大小。当设置为-1时,线程池将使用SynchronousQueue实现的队列,
        // 否则将使用LinkedBlockingQueue实现的队列
        @HystrixProperty(name = "maxQueueSize",value = "-1"),

        // 该参数用来为队列设置拒绝阈值。通过该参数,即使队列没有达到最大值也能拒绝请求。
        // 该参数主要是对LinkedBlockingQueue队列的补充,
        // 因为LinkedBlockingQueue队列不能动态修改它的对象大小,而通过该属性就可以调整拒绝请求的队列大小了。
        @HystrixProperty(name = "queueSizeRejectionThreshold",value = "5"),
})
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值