一篇文章搞懂hystrix,hystrix大全

Hystrix
1.服务雪崩

要想明白为什么会出现Hystrix和为什么要使用Hystrix,就要先明白一个知识点,就是服务雪崩,那么什么是服务雪崩,多个微服务之间在相互调用中,由于某一个服务节点瘫痪而导致的整个服务瘫痪,这种现象就叫做雪崩,比如说A服务调用B和C服务,B和C又调用其他微服务,如果这个时候有一个微服务出现问题,或这长时间未响应,对A微服务的占用的越来越多的系统资源。最后就会导致服务雪崩。

2.Hystrix的作用

Hystrix的作用就是为了防止上面说的由于某一个服务节点出问题而导致整个系统崩溃而出现的。Hystrix,是对雪崩效应的一种微服务链路的保护机制。Hystrix的功能主要是以下几个。

  • 服务降级
  • 服务熔断
  • 服务隔离
  • 服务监控
3.服务降级

当调用目标请求发生异常或者超时的时候,由Hystrix将请求转发到降级逻辑中,使请求可以正常返回,而不是占用大量系统资源。

3.1 服务降级流程

在这里插入图片描述

首先在需要服务降级的方法上打上@HystrixCommand注解,这样当调用到这个方法的时候就会利用spring中的aop调用切面方法,然后判断缓存是否开启,如果缓存开启则直接从缓存中取数据,如果缓存没有开启,就注册Observer,observer是观察者模式,运用的rxjava注册了很多异步的回调函数,当方法正常,异常或者超时后会调用不同的会调函数进行处理。发起调用后,如果异常,就会调用fallback处理。

3.2 服务降级的常用方案
  • 静默处理,在fallback中什么都不干,直接返回一个空null。
  • 默认值处理
  • 想办法恢复,例如如果是缓存异常,可以直接去调用数据库,如果是服务器异常,切换到备库处理。
  • 多重降级
3.3 服务降级代码演示

⚠️:这块的代码实例需要有eureka和fegin的基础

  1. 先引入pom
<dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>com.google.guava</groupId>
                    <artifactId>guava</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>
  1. 在启动类上添加注解
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
@EnableCircuitBreaker
public class HystrixFallbacakApplication {

    public static void main(String[] args) {
        new SpringApplicationBuilder(HystrixFallbacakApplication.class)
                .web(WebApplicationType.SERVLET)
                .run(args);
    }

}
  1. 创建fallback方法
@Component
@Slf4j
public class Fallback implements MyService{

    @Override
    public String error() {
        log.info("I'm not a black sheep any more");
        return "Fallback:I'm not a black sheep any more";
    }
    }
  1. 创建报错方法
@Override
    public String error(){
        throw new RuntimeException("black sheep");
    }
  1. 配置Feigin注解
@FeignClient(name = "feign-client",fallback = Fallback.class)
public interface MyService extends IService{
}
  1. 配置配置文件
spring:
  application:
    name: hystrix-consumer
  main:
    allow-bean-definition-overriding: true
server:
  port: 50000
eureka:
  client:
    service-url:
      defaultZone: http://localhost:20000/eureka/
## 启动hystrix
feign:
  hystrix:
    enabled: true

服务降级不只有服务异常所引起,也有可能是因为服务超时引起,超时配置有两种方式,下面看一下关于服务超时的配置项
配置文件配置

hystrix:
  command:
    default: #也可以针对多个服务
      execution:
        isolation:
          thread:
            timeoutInMilliseconds: 4000 # 设置hystrix的超时时间为4000ms
            interruptOnTimeout: true #设置是否在超时之后终止线程
            interruptOnFutureCancel: true #设置是否在取消的时候终止线程
        timeout:
          enabled: true #开启全局超时判定

注解方式配置

    @HystrixCommand(fallbackMethod = "timeoutfallback",
    commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "3000")
    })
3.4 Hystrix中的缓存

Hystrix提供了一种缓存机制,在调用一个方法的之后Hystrix会把这次的数据缓存起来,当下次调用的时候,就直接从缓存中获取,而不是再次调用,注意Hystrix的缓存是方法级别的,而不是像redis那种分布式缓存。

  • 第一步 在需要缓存的方法添加@CacheResult注解,表示这个方法需要缓存,然后参数上添加@CacheKey注解,这个就类似于map中的key,意味着缓存的建为这个参数
    @CacheResult
    @HystrixCommand
    public Friend requestCache(@CacheKey String name){
        log.info("request chche"+name);
        Friend friend = new Friend();
        friend.setName(name);
        friend = service.sayHi(friend);
        log.info("after requesting cache"+name);
        return friend;
    }
  • 第二步 打开Hystrix的上下文
@Cleanup HystrixRequestContext context =  HystrixRequestContext.initializeContext();
4. 服务熔断

服务熔断可以看成是服务降级的升级版,服务降级需要等待HTTP请求从服务节点返回异常或者超时,在转向降级逻辑中,而服务熔断增加了一个叫“熔断器”机制,当熔断器打开的时候请求会直接发送到容错机制中。

4.1 服务熔断逻辑

在这里插入图片描述

此处省略了服务降级的逻辑
首先发起调用然后被aop拦截,这个时候会去检查熔断器是否开启,如果熔断器已经开启,那么直接调用fallback的逻辑,如果熔断器没有开启,就是远程调用接口,如果远程调用接口出现问题,这个时候会上报metrics,metrics指的是衡量指标,在异常发生的时候会根据熔断器的配置参数计算是否达到了熔断标准,如果达到了则直接开启熔断器。
在这里插入图片描述

熔断器并不会一直开着,熔断器有三种状态,close,helf-open和open,当熔断器开启一段时间后会进入到helf-open阶段,在这个阶段当请求过来后会让一个请求去访问真实的远程接口,如果远程接口可用,则熔断器关闭,如果还是不可用,熔断器开启。

4.2 服务熔断参数配置
hystrix:
  command:
    default: #也可以针对多个服务
      metrics:
        rollingStats:
          timeInMillisseconds: 20000 #配置时间窗口
      circuitBreaker:
        requestVolumeThreshold: 5 # 熔断的前提条件(请求的数量),在一定时间窗口内,请求达到5个才会开始进行熔断判断
        errorThresholdPercentage: 50 # 超过50%的失败请求,则熔断开关开启
        sleepWindowInMilliseconds: 15000 # 设置当熔断开启后经过多少秒在进入半开状态
        #这段配置翻译过来就是当两秒内请求超过五个,并且其中失败的请求超过2两个,则熔断器开启
5. 服务隔离

服务隔离分为两种,一种是线程池隔离,一种是信号量隔离。首先说一下为什么需要线程隔离,线程池的目的主要是为了防止由于某一个请求占用太多的资源导致整个服务器奔溃的情况。

5.1 线程池隔离

Hystrix通过内部创建线程池,为每个服务设置单独的线程 ,然后每个单独的线程设置单独的线程数

5.2 信号量隔离

信号量隔离是通过信号量来进行判断,获得信号量的进行访问,如果没有获得信号量的直接调用fallback。

6.服务监控

hystrix可以通过turbine和dashboard两个组件来进行服务监控

6.1 turbine

Turbine就是用来聚合所有相关的 hystrix.stream 流的解决方案,最后在 Hystrix Dashboard 中显示出来。
添加依赖

<dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-turbine</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>com.google.guava</groupId>
                    <artifactId>guava</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

在启动类上添加注解

@EnableCircuitBreaker
@EnableHystrix
@EnableTurbine
@EnableAutoConfiguration
public class TurbineApplication {

    public static void main(String[] args) {
        new SpringApplicationBuilder(TurbineApplication.class)
                .web(WebApplicationType.SERVLET)
                .run(args);
    }


}

添加配置信息

spring:
  application:
    name: hystrix-trubine
server:
  port: 52000
management:
  server:
    port: 52001
eureka:
  client:
    service-url:
      defaultZone: http://localhost:20000/eureka/ # 服务注册地址
turbine:
  app-config: hystrix-consumer    #需要监听的服务
  cluster-name-expression: new String("default") #监听集群信息
  combine-host-port: true #按照host+port的形式筛选
  instanceUrlSuffix:
    default: actuator/hystrix.stream #收集数据的节点,配上之后就ip+端口/actuator/hystrix.stream
  aggregator:
    cluster-config: default #指定聚合哪些集群
6.2 dashboard

仪表盘,可以实时监控hystrix的各种状态
添加依赖

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

启动类增加注解

@SpringBootApplication
@EnableHystrixDashboard
public class HystrixDashboardApplication {


    public static void main(String[] args) {
        new SpringApplicationBuilder(HystrixDashboardApplication.class)
                .web(WebApplicationType.SERVLET)
                .run(args);
    }

}

启动项目后在浏览器访问ip+端口/hystrix
在这里插入图片描述

在下方浏览器中输入要监控的地址,然后点击Monitor Stream
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值