轻松的午后,就像你的微笑,温暖而愉快。

编程开发

Spring Cloud 微服务入门教程(十):Spring Cloud Hystrix 服务熔断和服务降级

2020年03月01日 09:45:36 · 本文共 4,286 字阅读时间约 15分钟 · 3,835 次浏览
Spring Cloud 微服务入门教程(十):Spring Cloud Hystrix 服务熔断和服务降级

上一节我们讲了服务网关,就可以让多个服务通过网关统一发布出去了,在发布出去之前我们还要了解一个机制,那就是微服务中的服务熔断和服务降级的机制,在 Spring Cloud 中叫 Hystrix,本节将整合 Hystrix 实现服务熔断和降级。Hystrix有很多特性,我们只说最常用的熔断和降级机制。

服务熔断是什么

我们先大概了解一下服务熔断是什么,在庞大的系统中服务之间会相互调用依赖,如果服务A需要调用服务B,但服务B因为某些故障或者网络故障导致服务A无法从服务B取得想要的数据,如果一直等待会造成线程阻塞和资源等待,拖慢整个系统数据流,甚至可能因为服务B挂掉以后服务A也挂掉,所以就需要熔断机制,当服务B的错误率超过一定比例(默认50%), 断路器就会熔断一段时间(默认5秒),不再去请求服务B,熔断时间过了以后再去尝试请求服务B,一旦依赖的端服务不可用, 断路器会切断请求链, 避免发送大量无效请求影响系统吞吐量, 并且断路器有自我检测并恢复的能力。那熔断时不请求服务B那去请求谁呢?就需要降级机制。

服务降级是什么

当我们依赖的服务故障就会触发熔断机制,此时你需要预先提供一个处理方法,作为降级的执行方法一般叫fallback,fallback返回值一般是设置的默认值或者来自缓存。告知后面的请求服务不可用了,比较经典的是淘宝抢购的时候告诉你服务器出小差了,这个就是服务降级,这个消息并不是来自后端的服务发出的,是前端的服务响应的。

添加依赖

我们在跟POM中添加依赖spring-cloud-starter-hystrix,代码如下:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>cloud</artifactId>
        <groupId>net.renfei</groupId>
        <version>1.0.0</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>
    <groupId>net.renfei</groupId>
    <artifactId>gateway</artifactId>
    <version>1.0.0</version>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-config</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-zuul</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-hystrix</artifactId>
        </dependency>
    </dependencies>
</project>

改造需要熔断机制的服务

在需要熔断服务的模块程序启动类上增加@EnableCircuitBreaker注解,根据之前的章节,我们现在应该一共具有了@EnableEurekaClient、@SpringBootApplication、@EnableCircuitBreaker这三个注解,其实这三个注解可以简化成一个@SpringCloudApplication,其实@SpringCloudApplication就包含了这三个注解了,所以我们删除这三个直接使用@SpringCloudApplication注解。

在需要熔断降级服务的类上面可以使用@DefaultProperties(defaultFallback = "defaultFallback")注解来定义一个默认的降级处理方法;在具体的方法上面可以使用@HystrixCommand(fallbackMethod = "fallbackMethod")注解来定义只有这个方法适用的的降级处理方法,因为要给大家演示如何自定义超时时间、熔断窗口时间、错误率等,所以我还增加了commandProperties的配置,这个是可以不写的,我是为了演示才写,里面是一个数组,所以可以配置多个@HystrixProperty,@HystrixProperty里面的key可以到com.netflix.hystrix.HystrixCommandProperties里面找。

我的示例是在democlient的controller里写的,你可以在service层里写熔断降级,我定义了一个默认的处理方法,同时也指定了一个并且指定了超时时间,代码如下:

package net.renfei.democlient.controller;
import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import net.renfei.apicenter.request.DemoRquest;
import net.renfei.apicenter.result.Result;
import net.renfei.democlient.client.DemoServiceClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@DefaultProperties(defaultFallback = "defaultFallback")
public class DemoClientController {
    @Autowired
    private DemoServiceClient demoServiceClient;
    
    @GetMapping("/")
    @HystrixCommand(
            fallbackMethod = "fallbackMethod",
            commandProperties = {
                    @HystrixProperty(name = "circuitBreaker.enabled", value = "true"),  //启用熔断
                    @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "10"),  //10秒内多少个请求才会起作用
                    @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "1000"),  //熔断窗口时间
                    @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "60"),  //错误阈值百分比
                    @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "1000")  //超时时间
            })
    public String getDemoService() {
        DemoRquest demoRquest = new DemoRquest();
        demoRquest.setMsg("This DemoRquest.Msg From DemoClientController.");
        Result result = demoServiceClient.sayMsg(demoRquest);
        return "You're visiting DemoClient. Call DemoService:{" + result.getMessage() + "}";
    }
    
    public String fallbackMethod() {
        return "DemoService服务有点问题,请稍后再试";
    }
    
    public String defaultFallback() {
        return "这是默认的Fallback方法";
    }
}

网关Zuul的超时配置

网关Zuul在转发时并没有Controller,那怎么配置呢,我们可以在配置文件中进行配置,我为了方便演示直接写在bootstrap.yml,代码如下:

hystrix:
  command:
    default:
      execution:
        isolation:
          thread:
            timeoutInMilliseconds : 5000

如果要测试我们的降级机制,只需要在demoservice提供服务的方法中sleep5秒即可,就可以触发降级机制。

商业用途请联系作者获得授权。
版权声明:本文为博主「任霏」原创文章,遵循 CC BY-NC-SA 4.0 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://www.renfei.net/posts/1003331
评论与留言

以下内容均由网友提交发布,版权与真实性无法查证,请自行辨别。

微信搜一搜:任霏博客