Spring Boot + Spring Cloud 实现权限管理系统 后端篇(二十):服务熔断(Hystrix、Turbine)

在线演示

演示地址:http://139.196.87.48:9002/kitty

用户名:admin 密码:admin

雪崩效应

在微服务架构中,由于服务众多,通常会涉及多个服务层级的调用,而一旦基础服务发生故障,很可能会导致级联故障,进而造成整个系统不可用,这种现象被称为服务雪崩效应。服务雪崩效应是一种因“服务提供者”的不可用导致“服务消费者”的不可用,并将这种不可用逐渐放大的过程。

比如在一个系统中, A作为服务提供者,B是A的服务消费者,C和D又是B的服务消费者。如果此时A发生故障,则会引起B的不可用,而B的不可用又将导致C和D的不可用,当这种不可用像滚雪球一样逐渐放大的时候,雪崩效应就形成了。

熔断器(CircuitBreaker)

熔断器的原理很简单,如同电力过载保护器。它可以实现快速失败,如果它在一段时间内侦测到许多类似的错误,就会强迫其以后的多个调用快速失败,不再访问远程服务器,从而防止应用程序不断地尝试执行可能会失败的操作,使得应用程序继续执行而不用等待修正错误,或者浪费CPU时间去等到长时间的超时产生。熔断器也可以使应用程序能够诊断错误是否已经修正,如果已经修正,应用程序会再次尝试调用操作。熔断器模式就像是那些容易导致错误的操作的一种代理。这种代理能够记录最近调用发生错误的次数,然后决定使用允许操作继续,或者立即返回错误。熔断器是保护服务高可用的最后一道防线。

Hystrix特性

1.断路器机制

断路器很好理解, 当Hystrix Command请求后端服务失败数量超过一定比例(默认50%), 断路器会切换到开路状态(Open). 这时所有请求会直接失败而不会发送到后端服务. 断路器保持在开路状态一段时间后(默认5秒), 自动切换到半开路状态(HALF-OPEN). 这时会判断下一次请求的返回情况, 如果请求成功, 断路器切回闭路状态(CLOSED), 否则重新切换到开路状态(OPEN). Hystrix的断路器就像我们家庭电路中的保险丝, 一旦后端服务不可用, 断路器会直接切断请求链, 避免发送大量无效请求影响系统吞吐量, 并且断路器有自我检测并恢复的能力。

2.Fallback

Fallback相当于是降级操作. 对于查询操作, 我们可以实现一个fallback方法, 当请求后端服务出现异常的时候, 可以使用fallback方法返回的值. fallback方法的返回值一般是设置的默认值或者来自缓存。

3.资源隔离

在Hystrix中, 主要通过线程池来实现资源隔离. 通常在使用的时候我们会根据调用的远程服务划分出多个线程池. 例如调用产品服务的Command放入A线程池, 调用账户服务的Command放入B线程池. 这样做的主要优点是运行环境被隔离开了. 这样就算调用服务的代码存在bug或者由于其他原因导致自己所在线程池被耗尽时, 不会对系统的其他服务造成影响. 但是带来的代价就是维护多个线程池会对系统带来额外的性能开销. 如果是对性能有严格要求而且确信自己调用服务的客户端代码不会出问题的话, 可以使用Hystrix的信号模式(Semaphores)来隔离资源。

Feign Hystrix

因为 Feign 中已经依赖了 Hystrix, 所以在 maven 配置上不用做任何改动就可以使用了,我们在 kitty-consumer 项目中直接改造。

修改配置

在配置文件中添加配置,开启 Hystrix 熔断器。

application.yml

#开启熔断器
feign:
  hystrix:
    enabled: true

创建回调类

创建一个回调类 KittyProducerHystrix,实现 KittyProducerService接口,并实现对应的方法,返回调用失败后的信息。

KittyProducerHystrix.java

package com.louis.kitty.consumer.feign;

import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;

@Component
public class KittyProducerHystrix implements KittyProducerService {

    @RequestMapping("/hello")
    public String hello() {
        return "sorry, hello service call failed.";
    }
}

添加fallback属性

修改 KittyProducerService,在 @FeignClient 注解中加入 fallback 属性,绑定我们创建的失败回调处理类。

package com.louis.kitty.consumer.feign;

import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;

@FeignClient(name = "kitty-producer", fallback = KittyProducerHystrix.class)
public interface KittyProducerService {

    @RequestMapping("/hello")
    public String hello();
}

到此,所有改动代码就完成了。

测试效果

启动成功之后,多次访问 http://localhost:8005/feign/call,结果如同之前一样交替返回 hello kitty 和 hello kitty 2。

说明熔断器的启动,不会影响正常服务的访问。

 

把 kitty-producer 服务停掉,再次访问,返回我们提供的熔断回调信息,熔断成功,kitty-producer2服务正常。

 

重启 kitty-producer 服务,再次访问,发现服务又可以访问了,说明熔断器具有自我诊断修复的功能。

注意:在重启成功之后,可能需要一些时间,等待熔断器进行自我诊断和修复完成之后,方可正常提供服务。

  

Hystrix Dashboard

Hystrix-dashboard是一款针对Hystrix进行实时监控的工具,通过Hystrix Dashboard我们可以在直观地看到各Hystrix Command的请求响应时间, 请求成功率等数据。

添加依赖

新建一个 kitty-hystrix 工程,修改 pom 文件,添加相关依赖。

pom.xml

<!-- spring boot -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter</artifactId>
</dependency>
<!--consul-->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-consul-discovery</artifactId>
</dependency>
<!--actuator-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<!--spring-boot-admin-->
<dependency>
    <groupId>de.codecentric</groupId>
    <artifactId>spring-boot-admin-starter-client</artifactId>
    <version>${spring.boot.admin.version}</version>
</dependency>
<!--hystrix-dashboard-->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-hystrix-dashboard</artifactId>
</dependency>

Spring Cloud Pom依赖。

<!--srping cloud-->
<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>${spring-cloud.version}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

启动类

在启动类中添加注解 @EnableHystrixDashboard 开启熔断监控支持。

KittyHystrixApplication.java

package com.louis.kitty.hystrix;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.hystrix.dashboard.EnableHystrixDashboard;
import org.springframework.cloud.netflix.turbine.EnableTurbine;

/**
 * 启动器
 * @author Louis
 * @date Oct 29, 2018
 */
@EnableHystrixDashboard
@EnableDiscoveryClient
@SpringBootApplication
public class KittyHystrixApplication {

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

配置文件

修改配置文件,把服务注册到注册中心。

server:
  port: 8501
spring:
  application:
    name: kitty-hystrix
  cloud:
    consul:
      host: localhost
      port: 8500
      discovery:
        serviceName: ${spring.application.name}    # 注册到consul的服务名称

配置监控路径

注意,如果你使用的是2.x等比较新的版本,需要在 Hystrix 的消费端配置监控路径。

打开消费端 kitty-consumer 工程, 添加依赖。

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

修改启动类,添加服务监控路径配置。

ConsuleConsumerApplication.java

// 此配置是为了服务监控而配置,与服务容错本身无关,
// ServletRegistrationBean因为springboot的默认路径不是"/hystrix.stream",
// 只要在自己的项目里配置上下面的servlet就可以了
@Bean
public ServletRegistrationBean getServlet() {
    HystrixMetricsStreamServlet streamServlet = new HystrixMetricsStreamServlet();
    ServletRegistrationBean registrationBean = new ServletRegistrationBean(streamServlet);
    registrationBean.setLoadOnStartup(1);
    registrationBean.addUrlMappings("/hystrix.stream");
    registrationBean.setName("HystrixMetricsStreamServlet");
    return registrationBean;
}

测试效果

先后启动 monitor、producer、consumer、hystrix 服务。

访问 http://localhost:8501/hystrix,会看到如下图所示界面。

此时没有任何具体的监控信息,需要输入要监控的消费者地址及监控信息的轮询时间和标题。

Hystrix Dashboard 共支持三种不同的监控方式:

单体Hystrix 消费者:通过URL http://hystrix-app:port/hystrix.stream 开启,实现对具体某个服务实例的监控。

默认集群监控:通过URL http://turbine-hostname:port/turbine.stream 开启,实现对默认集群的监控。

自定集群监控:通过URL http://turbine-hostname:port/turbine.stream?cluster=[clusterName] 开启,实现对clusterName集群的监控。

我们这里现在是对单体 Hystrix 消费者的监控,后面整合 Turbine 集群的时候再说明后两种的监控方式。

我们先访问 http://localhost:8005/feign/call, 查看要监控的服务是否可以正常访问。

确认服务可以正常访问之后,在监控地址内输入 http://localhost:8005/hystrix.stream,然后点击 Monitor Stream 开始监控。


刚进去,页面先显示 loading... 信息, 多次访问 http://localhost:8005/feign/call 之后,统计图表信息如下图所示。

各个指标的含义参见下图。

Spring Cloud Turbine

上面我们集成了Hystrix Dashboard使用Hystrix Dashboard可以看到单个应用内的服务信息,显然这是不够的,我们还需要一个工具能让我们汇总系统内多个服务的数据并显示到Hystrix Dashboard上,这个工具就是Turbine。

添加依赖

修改 kitty-hystrix 的pom文件,添加 turbine 依赖包。

注意:因为我们使用的注册中心是Consul,所以需要排除默认的euraka包,不然会有冲突启动出错。

pom.xml

<!--turbine-->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-turbine</artifactId>
    <exclusions>  
         <exclusion>     
              <groupId>org.springframework.cloud</groupId>
              <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
         </exclusion>  
    </exclusions> 
</dependency>

启动类

启动类添加 @EnableTurbine 注解,开启 turbine 支持。

KittyHystrixApplication.java

package com.louis.kitty.hystrix;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.hystrix.dashboard.EnableHystrixDashboard;
import org.springframework.cloud.netflix.turbine.EnableTurbine;

/**
 * 启动器
 * @author Louis
 * @date Oct 29, 2018
 */
@EnableTurbine
@EnableHystrixDashboard
@EnableDiscoveryClient
@SpringBootApplication
public class KittyHystrixApplication {

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

配置文件

修改配置,配置注册服务信息,添加turbine配置。

application.yml

turbine:
  instanceUrlSuffix: hystrix.stream    # 指定收集路径
  appConfig: kitty-consumer    # 指定了需要收集监控信息的服务名,多个以“,”进行区分
  clusterNameExpression: "'default'"    # 指定集群名称,若为default则为默认集群,多个集群则通过此配置区分
  combine-host-port: true    # 此配置默认为false,则服务是以host进行区分,若设置为true则以host+port进行区分

测试效果

依次启动 monitor、producer、consumer,hystrix 服务,访问 http://localhost:8500  查看注册中心管理界面。

 

确认服务无误之后, 访问 http://localhost:8501/hystrix,输入 http://localhost:8501/turbine.stream,查看监控图表。

如下图所示,就是利用 Turbine 聚合多个 Hytrix 消费者的熔断监控信息结果,内存允许可以多启动几个消费者查看

源码下载

后端:https://gitee.com/liuge1988/kitty

前端:https://gitee.com/liuge1988/kitty-ui.git


作者:朝雨忆轻尘
出处:https://www.cnblogs.com/xifengxiaoma/ 
版权所有,欢迎转载,转载请注明原文作者及出处。

猜你喜欢

转载自www.cnblogs.com/xifengxiaoma/p/9910326.html