Hystrix 断路器

零碎容错工具

  • 降级

    • 调用近程服务失败(宕机、500错、超时),能够降级执行以后服务中的一段代码,向客户端返回后果
    • 疾速失败
  • 熔断

    • 当拜访量过大,呈现大量失败,能够做过热爱护,断开近程服务不再调用
    • 限流
    • 避免故障流传、雪崩效应
  • https://github.com/Netflix/Hystrix/wiki

Hystrix降级

  1. hystrix依赖
  2. 启动类增加注解 @EnableCircuitBreaker
  3. 增加降级代码
// 当调用近程服务失败,跳转到指定的办法,执行降级代码@HystrixCommand(fallbackMethod="办法名")近程调用办法() { restTemplate.getForObject(url,......);}
微服务宕机时,ribbon 无奈转发申请
  • 敞开 user-service 和 order-service



阐明:这是没有hystrix的状况,下来测试hystrix提供的降级解决形式

复制 sp06-ribbon 我的项目,命名为sp07-hystrix
  • 抉择 sp06-ribbon 我的项目,ctrl-c,ctrl-v,复制为sp07-hystrix
  • 敞开 sp06-ribbon 我的项目,后续测试应用 sp07-hystrix 我的项目

批改 pom.xml

增加 hystrix 起步依赖
`<dependency>    <groupId>org.springframework.cloud</groupId>    <artifactId>spring-cloud-starter-netflix-hystrix</artifactId></dependency>` 
批改 application.yml

spring:  application:    name: hystrix    server:  port: 3001  eureka:  client:        service-url:      defaultZone: http://eureka1:2001/eureka, http://eureka2:2002/eureka      ribbon:  MaxAutoRetries: 1  MaxAutoRetriesNextServer: 2  OkToRetryOnAllOperations: true

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

启动断路器,断路器提供两个外围性能:

  • 降级,超时、出错、不可达到时,对服务降级,返回错误信息或者是缓存数据
  • 熔断,当服务压力过大,谬误比例过多时,熔断所有申请,所有申请间接降级
  • 能够应用 @SpringCloudApplication 注解代替三个注解
package cn.tedu.sp06;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@SpringCloudApplicationpublic 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);    }}

RibbonController 中增加降级办法

  • 为每个办法增加降级办法,例如 getItems() 增加降级办法 getItemsFB()
  • 增加 @HystrixCommand 注解,指定降级办法名
package cn.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@Slf4jpublic class RibbonController {    @Autowired    private RestTemplate restTemplate;    @HystrixCommand(fallbackMethod = "getItemsFB") //指定降级办法的办法名    @GetMapping("/item-service/{orderId}")    public JsonResult<List<Item>> getItems(@PathVariable String orderId){        //近程调用商品服务        //http://localhost:8001/{orderId}        //{1} -- RestTemplate 定义的一种占位符格局,传递参数orderId        //return restTemplate.getForObject("http://localhost:8001/{1}",JsonResult.class,orderId);        return restTemplate.getForObject("http://item-service/{1}",JsonResult.class,orderId);//Ribbon的形式,将ip:port改为服务名称    }    @HystrixCommand(fallbackMethod = "decreaseNumberFB") //指定降级办法的办法名    @PostMapping("/item-service/decreaseNumber")    public JsonResult<?> decreaseNumber(@RequestBody List<Item> items){        return restTemplate.postForObject("http://item-service/decreaseNumber", items, JsonResult.class);    }    // -----------------------    @HystrixCommand(fallbackMethod = "getUserFB") //指定降级办法的办法名    @GetMapping("/user-service/{userId}")    public JsonResult<User> getUser(@PathVariable Integer userId){        return restTemplate.getForObject("http://user-service/{1}", JsonResult.class,userId);    }    @HystrixCommand(fallbackMethod = "addScoreFB") //指定降级办法的办法名    @GetMapping("/user-service/{userId}/score")    public JsonResult<?> addScore(@PathVariable Integer userId,Integer score){        return restTemplate.getForObject("http://user-service/{1}/score?score={2}", JsonResult.class,userId,score);    }    @HystrixCommand(fallbackMethod = "getOrderFB") //指定降级办法的办法名    @GetMapping("/order-service/{orderId}")    public JsonResult<Order> getOrder(@PathVariable String orderId){        return restTemplate.getForObject("http://order-service/{1}", JsonResult.class,orderId);    }    @HystrixCommand(fallbackMethod = "addOrderFB") //指定降级办法的办法名    @GetMapping("/order-service/")    public JsonResult<?> addOrder(){        return restTemplate.getForObject("http://order-service/", JsonResult.class);    }    // -----------------------    //降级办法的参数和返回值,须要和原始办法统一,办法名任意    public JsonResult<List<Item>> getItemsFB(String orderId){        return JsonResult.err("获取订单商品列表失败");    }    public JsonResult<?> decreaseNumberFB(List<Item> items){        return JsonResult.err("更新商品库存失败");    }    public JsonResult<User> getUserFB(Integer userId){        return JsonResult.err("获取用户信息失败");    }    public JsonResult<?> addScoreFB(Integer userId,Integer score){        return JsonResult.err("减少用户积分失败");    }    public JsonResult<Order> getOrderFB(String orderId){        return JsonResult.err("获取订单失败");    }    public JsonResult<?> addOrderFB(){        return JsonResult.err("增加订单失败");    }}
hystrix 超时设置

hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds
hystrix期待超时后, 会执行降级代码, 疾速向客户端返回降级后果, 默认超时工夫是1000毫秒
为了测试 hystrix 降级,咱们把 hystrix 期待超时设置得十分小(1000毫秒)
此设置个别应大于 ribbon 的重试超时时长,例如 10 秒

spring:  application:    name: hystrixserver:  port: 3001eureka:  client:    service-url:      defaultZone: http://eureka1:2001/eureka,http://eureka2:2002/eureka# 配置 Ribbon 重试次数ribbon:  # 次数参数没有提醒,并且会有黄色正告  # 重试次数越少越好,个别倡议用0 ,1  MaxAutoRetries: 1  MaxAutoRetriesNextServer: 2#配置hystrix超时设置 疾速向客户端返回降级后果, 默认超时工夫是1000毫秒hystrix:  command:    default:      execution:        isolation:          thread:            timeoutInMilliseconds: 1000

启动我的项目进行测试

  • 通过 hystrix 服务,拜访可能超时失败的 item-service
    http://localhost:3001/item-service/35
  • 通过 hystrix 服务,拜访未启动的 user-service
    http://localhost:3001/user-service/7
  • 能够看到,如果 item-service 申请超时,hystrix 会立刻执行降级办法
  • 拜访 user-service,因为该服务未启动,hystrix也会立刻执行降级办法

hystrix dashboard 断路器仪表盘

hystrix 对申请的降级和熔断,能够产生监控信息,hystrix dashboard能够实时的进行监控

Actuator

springboot 提供的日志监控工具,能够裸露我的项目中多种监控信息

  • 衰弱状态
  • 零碎环境变量
  • spring容器中所有的对象
  • spring mvc映射的所有门路
  • ......

增加 actuator

  1. 增加 actuator 依赖
  2. yml 配置裸露监控数据

    • m.e.w.e.i="*" 裸露所有的监控
    • m.e.w.e.i=health 只裸露衰弱状态
    • m.e.w.e.i=["health", "beans", "mappings"] 裸露指定的多个监控

sp07-hystrix 我的项目增加 actuator,并裸露 hystrix 监控端点

actuator 是 spring boot 提供的服务监控工具,提供了各种监控信息的监控端点
management.endpoints.web.exposure.include 配置选项,
能够指定端点名,来裸露监控端点
如果要裸露所有端点,能够用 “*”

pom.xml 增加 actuator 依赖

右键点击我的项目或pom.xml, 编辑起步依赖, 增加 actuator 依赖

<dependency>    <groupId>org.springframework.boot</groupId>    <artifactId>spring-boot-starter-actuator</artifactId></dependency>
调整 application.yml 配置,并裸露 hystrix.stream 监控端点
spring:  application:    name: hystrixserver:  port: 3001eureka:  client:    service-url:      defaultZone: http://eureka1:2001/eureka,http://eureka2:2002/eureka# 配置 Ribbon 重试次数ribbon:  # 次数参数没有提醒,并且会有黄色正告  # 重试次数越少越好,个别倡议用0 ,1  MaxAutoRetries: 1  MaxAutoRetriesNextServer: 2#配置hystrix超时设置 疾速向客户端返回降级后果, 默认超时工夫是1000毫秒hystrix:  command:    default:      execution:        isolation:          thread:            timeoutInMilliseconds: 1000#配置actuator,裸露hystrix.stream监控端点management:  endpoints:    web:      exposure:        include: "*"
拜访 actuator 门路,查看监控端点
  • http://localhost:3001/actuator

Hystrix dashboard 仪表盘

搭建 Hystrix Dashboard

仪表盘我的项目能够是一个齐全独立的我的项目,与其余我的项目都无关,也不必向注册表注册

  1. hystrix dashboard 依赖
  2. @EnableHystrixDashboard
  3. yml - 容许对哪台服务器开启监控
hystrix: dashboard: proxy-stream-allow-list: localhost

新建 sp08-hystrix-dashboard 我的项目

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>
application.yml
spring:  application:    name: hystrix-dashboard    server:  port: 4001eureka:  client:    service-url:      defaultZone: http://eureka1:2001/eureka, http://eureka2:2002/eurekahystrix:  dashboard:    proxy-stream-allow-list: localhost
主程序增加 @EnableHystrixDashboard@EnableDiscoveryClient
package cn.tedu.sp08;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;@EnableDiscoveryClient@EnableHystrixDashboard@SpringBootApplicationpublic class Sp08HystrixDashboardApplication {    public static void main(String[] args) {        SpringApplication.run(Sp08HystrixDashboardApplication.class, args);    }}

启动,并拜访测试

拜访 hystrix dashboard
  • http://localhost:4001/hystrix

填入 hystrix 的监控端点,开启监控
  • http://localhost:3001/actuator/hystrix.stream

  • 通过 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/

Hystrix 熔断

短路器关上的条件:

  • 10秒内20次申请(必须首先满足)
  • 50%失败,执行了降级代码
短路器关上后,所有申请间接执行降级代码断路器关上几秒后,会进入**半开状态**,客户端调用会尝试向后盾服务发送一次调用,如果调用胜利,断路器能够主动敞开,恢复正常如果调用依然失败,持续放弃关上状态几秒钟

整个链路达到肯定的阈值,默认状况下,10秒内产生超过20次申请,则合乎第一个条件。
满足第一个条件的状况下,如果申请的谬误百分比大于阈值,则会关上断路器,默认为50%。
Hystrix的逻辑,先判断是否满足第一个条件,再判断第二个条件,如果两个条件都满足,则会开启断路器

断路器关上 5 秒后,会处于半开状态,会尝试转发申请,如果依然失败,放弃关上状态,如果胜利,则敞开断路器

应用 apache 的并发拜访测试工具 ab

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

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