一、Hystrix

系统容错、限流工具
image.png

1.降级

当一个服务调用一个后台服务调用失败(异常、服务不存在、超时),可以执行当前服务中的一段“降级代码”,来返回降级结果
快速失败: 当调用后台服务超时,为了不让用户长时间等待,可以直接返回降级结果

1.1添加降级:

1.1.1 创建 sp07-hystrix 项目

image.png

1.1.2 添加 hystrix 依赖

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

1.1.3 修改 application.yml

spring:
  application:
    name: hystrix
server:
  port: 3001
#连接eureka
eureka:
  client:
    service-url:
      defaultZone: http://eureka1:2001/eureka, http://eureka2:2002/eureka
ribbon:
  #单台重试次数
 MaxAutoRetries: 1
  #更换服务器次数
 MaxAutoRetriesNextServer: 2

1.1.4 主程序添加 @EnableCircuitBreaker 启用 hystrix 断路器

启动断路器,断路器提供两个核心功能:

  • 降级,超时、出错、不可到达时,对服务降级,返回错误信息或者是缓存数据
  • 熔断,当服务压力过大,错误比例过多时,熔断所有请求,所有请求直接降级
  • 可以使用 @SpringCloudApplication 注解代替三个注解
package cn.tedu.sp07;
import org.springframework.boot.SpringApplication;
import org.springframework.cloud.client.SpringCloudApplication;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
//@EnableCircuitBreaker
//@EnableDiscoveryClient
//@SpringBootApplication
@SpringCloudApplication
public class Sp06RibbonApplication {
    @LoadBalanced
    @Bean
    public RestTemplate getRestTemplate() {
        SimpleClientHttpRequestFactory f = new SimpleClientHttpRequestFactory();
        f.setConnectTimeout(1000);
        f.setReadTimeout(1000);
        return new RestTemplate(f);
        //RestTemplate 中默认的 Factory 实例中,两个超时属性默认是 -1,
        //未启用超时,也不会触发重试
        //return new RestTemplate();
    }
    public static void main(String[] args) {
        SpringApplication.run(Sp06RibbonApplication.class, args);
    }
}

1.1.5 RibbonController 中添加降级方法

  • 为每个方法添加降级方法,例如 getItems() 添加降级方法 getItemsFB()
  • 添加 @HystrixCommand 注解,指定降级方法名
package com.tedu.sp06.controller;
import cn.tedu.sp01.pojo.Item;
import cn.tedu.sp01.pojo.Order;
import cn.tedu.sp01.pojo.User;
import cn.tedu.web.util.JsonResult;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import java.util.List;
@RestController
@Slf4j
public class RibbonController {
    @Autowired
 private RestTemplate rt;
    @GetMapping("/item-service/{orderId}")
    @HystrixCommand(fallbackMethod = "getItemsFB")
    public JsonResult<List<Item>> getItems(@PathVariable String orderId) {
        /*调用远程的商品服务,获得订单的商品列表
 {1} - RestTemplate自己定义的一种站位符格式
 注册中心的注册表:
 item-service ---- localhost:8001,localhost:8002 从注册表得到 item-service 对应的多个地址,然后在多个地址之间来回调用
 */ return rt.getForObject("http://item-service/{1}", JsonResult.class, orderId); //用 orderId 填充占位符 {1} }
    @PostMapping("/item-service/decreaseNumber")
    @HystrixCommand(fallbackMethod = "decreaseNumberFB")
    public JsonResult<?> decreaseNumber(@RequestBody List<Item> items) {
        return rt.postForObject("http://item-service/decreaseNumber", items, JsonResult.class);
    }
    @GetMapping("/user-service/{userId}")
    @HystrixCommand(fallbackMethod = "getUserFB")
    public JsonResult<User> getUser(@PathVariable Integer userId) {
        return rt.getForObject("http://user-service/{1}", JsonResult.class, userId);
    }
    @GetMapping("/user-service/{userId}/score") // ?score=1000
 @HystrixCommand(fallbackMethod = "addScoreFB")
    public JsonResult<?> addScore(@PathVariable Integer userId, @RequestParam Integer score) {
        return rt.getForObject("http://user-service/{1}/score?score={2}", JsonResult.class, userId, score);
    }
    @GetMapping("/order-service/{orderId}")
    @HystrixCommand(fallbackMethod = "getOrderFB")
    public JsonResult<Order> getOrder(@PathVariable String orderId) {
        return rt.getForObject("http://order-service/{1}", JsonResult.class, orderId);
    }
    @GetMapping("/order-service")
    @HystrixCommand(fallbackMethod = "addOrderFB")
    public JsonResult<?> addOrder() {
        return rt.getForObject("http://order-service", JsonResult.class);
    }
    //////////////////////////////////////////////////////////////
 public JsonResult<List<Item>> getItemsFB(String orderId) {
        return JsonResult.err().msg("获取订单商品列表失败");
    }
    public JsonResult<?> decreaseNumberFB( List<Item> items) {
        return JsonResult.err().msg("减少商品库存失败");
    }
    public JsonResult<User> getUserFB( Integer userId) {
        return JsonResult.err().msg("获取用户失败");
    }
    public JsonResult<?> addScoreFB(Integer userId, @RequestParam Integer score) {
        return JsonResult.err().msg("增加用户积分失败");
    }
    public JsonResult<Order> getOrderFB (String orderId){
        return JsonResult.err().msg("获取订单失败");
    }
    public JsonResult<?> addOrderFB () {
        return JsonResult.err().msg("添加订单失败");
    }
}

1.2 添加 hystrix 超时设置

hystrix等待超时后, 会执行降级代码, 快速向客户端返回降级结果, 默认超时时间是1000毫秒
为了测试 hystrix 降级,我们把 hystrix 等待超时设置得非常小(500毫秒)
此设置一般应大于 ribbon 的重试超时时长,例如 10 秒

spring:
  application:
    name: hystrix
server:
  port: 3001
#连接eureka
eureka:
  client:
    service-url:
      defaultZone: http://eureka1:2001/eureka, http://eureka2:2002/eureka
ribbon:
  #单台重试次数
 MaxAutoRetries: 1
  #更换服务器次数
 MaxAutoRetriesNextServer: 2
#超时设置
hystrix:
  command:
    default:
      execution:
        isolation:
          thread:
            timeoutInMilliseconds: 1000

1.1.6 启动项目进行测试

image.png

降级

2. 熔断

服务过热,直接把后台服务断开,限制服务的请求流量
在特定条件下回自动触发熔断:

  • 10秒20次请求(必须首选满足)
  • 50%失败,执行了降级代码

熔断后(断路器打开),所有请求直接执行降级代码,返回降级结果
半开状态:
断路器打开后几秒,会进入半开状态,会向后台服务尝试发送一次用户请求,如果成功则关闭断路器,恢复正常。如果失败,继续保持短路器打开状态几秒 。

二、Hystrix Dashboard

Hystrix 仪表盘,故障监控

1. actuator

image.png
springboot 提供的项目监控信息工具,提供项目的各种监控日志数据

  • 健康状态
  • spring 容器中所有的对象
  • spring mvc 所有的映射路径
  • env 环境变量
  • ......

hystrix利用 actuator 暴露了自己的监控日志,日志端点:hystrix.stream

1.1 pom.xml 添加 actuator 依赖

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

1.2 调整 application.yml 配置,并暴露 hystrix.stream 监控端点

spring:
  application:
    name: ribbon   #hystrix
server:
  port: 3001
#连接eureka
eureka:
  client:
    service-url:
      defaultZone: http://eureka1:2001/eureka, http://eureka2:2002/eureka
ribbon:
  #单台重试次数
 MaxAutoRetries: 1
  #更换服务器次数
 MaxAutoRetriesNextServer: 2
#超时设置
hystrix:
  command:
    default:
      execution:
        isolation:
          thread:
            timeoutInMilliseconds: 1000
management:
  endpoints:
    web:
      exposure:
        include: "*"

1.3 访问 actuator 路径,查看监控端点

image.png

2. Hystrix dashboard 仪表盘

image.png

2.1 新建 sp08-hystrix-dashboard 项目

image.png

2.2 修改 pom.xml 文件

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.1.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>cn.tedu</groupId>
    <artifactId>sp08-hystrix-dashboard</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>sp08-hystrix-dashboard</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
        <spring-cloud.version>Hoxton.RELEASE</spring-cloud.version>
    </properties>

    <dependencies>
        <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-hystrix-dashboard</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <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>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

2.3 修改 application.yml 文件

spring:
  application:
    name: hystrix-dashboard
server:
  port: 4001
#允许从这些服务器抓取日志
hystrix:
  dashboard:
    proxy-stream-allow-list: localhost

2.4 主程序添加 @EnableHystrixDashboard 注解

package com.tedu.sp08;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.hystrix.dashboard.EnableHystrixDashboard;
@EnableHystrixDashboard
@SpringBootApplication
public class Sp08HystrixDashboardApplication {
   public static void main(String[] args) {
      SpringApplication.run(Sp08HystrixDashboardApplication.class, args);
   }
}

2.5 启动,并访问测试

image.png

2.5.1 访问 hystrix dashboard

dashboard

2.5.2填入 hystrix 的监控端点,开启监控

开启监控

  • 通过 hystrix 访问服务多次,观察监控信息

http://localhost:3001/item-service/35
http://localhost:3001/user-service/7
http://localhost:3001/user-service/7/score?score=100
http://localhost:3001/order-service/123abc
http://localhost:3001/order-service/
监控界面
监控界面

3. 使用 apache 的并发访问测试工具 ab

http://httpd.apache.org/docs/current/platform/windows.html#down
下载Apache

  • 用 ab 工具,以并发50次,来发送20000个请求
`ab -n 20000 -c 50 http://localhost:3001/item-service/35` 
  • 断路器状态为 Open,所有请求会被短路,直接降级执行 fallback 方法

熔断
hystrix 配置
https://github.com/Netflix/Hystrix/wiki/Configuration

  • hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds
    请求超时时间,超时后触发失败降级
  • hystrix.command.default.circuitBreaker.requestVolumeThreshold
    10秒内请求数量,默认20,如果没有达到该数量,即使请求全部失败,也不会触发断路器打开
  • hystrix.command.default.circuitBreaker.errorThresholdPercentage
    失败请求百分比,达到该比例则触发断路器打开
  • hystrix.command.default.circuitBreaker.sleepWindowInMilliseconds
    断路器打开多长时间后,再次允许尝试访问(半开),仍失败则继续保持打开状态,如成功访问则关闭断路器,默认 5000

小韩
7 声望7 粉丝

及时更新,及时复习。