SpringCloud 07 - OpenFeign 服务接口调用
1. 概述
1.1 分布式系统面临的问题
复杂分布式体系结构中的应用程序:
服务雪崩:
多个微服务之间调用的时候,假设微服务 A 调用微服务 B 和微服务 C,微服务 B 和微服务 C 又调用其它的微服务,这就是所谓的 “扇出”。如果扇出的链路上某个微服务的调用响应时间过长或者不可用,对微服务 A 的调用就会占用越来越多的系统资源,进而引起系统崩溃,所谓的 “雪崩效应”。
对于高流量的应用来说,单一的后端依赖可能会导致所有服务器上的所有资源都在几秒钟内饱和。比失败更糟糕的是,这些应用程序还可能导致服务之间的延迟增加,备份队列,线程和其他系统资源紧张,导致整个系统发生更多的级联故障。这些都表示需要对故障和延迟进行隔离和管理,以便单个依赖关系的失败,不能取消整个应用程序或系统。
所以,通常当你发现一个模块下的某个实例失败后,这时候这个模块依然还会接收流量,然后这个有问题的模块还调用了其他的模块,这样就会发生级联故障,或者叫雪崩。
1.2 Hystrix 简介
官网:Home · Netflix/Hystrix Wiki · GitHub
Hystrix 是一个用于处理分布式系统的延迟和容错的开源库,在分布式系统里,许多依赖不可避免的会调用失败,比如超时、异常等,Hystrix 能够保证在一个依赖出问题的情况下,不会导致整体服务失败,避免级联故障,以提高分布式系统的弹性。
"断路器” 本身是一种开关装置,当某个服务单元发生故障之后,通过断路器的故障监控(类似熔断保险丝),向调用方返回一个符合预期的、可处理的备选响应(FallBack), 而不是长时间的等待或者抛出调用方无法处理的异常,这样就保证了服务调用方的线程不会被长时间、不必要地占用,从而避免了故障在分布式系统中的蔓延,乃至雪崩。
Hystrix官宣,停更进维。
1.3 作用
① 服务降级(fallback)
服务器忙,请稍后再试。不让客户端等待并立刻返回一个友好提示,fallback。
哪些情况会发出降级:
- 程序运行异常
- 超时
- 服务熔断触发服务降级
- 线程池 / 信号量也会导致服务降级
② 服务熔断(break)
类比保险丝达到最大服务访问后,直接拒绝访问,拉闸限电,然后调用服务降级的方法并返回友好提示。
就是保险丝:服务的降级 -> 进而熔断 -> 恢复调用链路
③ 服务限流(flowlimit)
秒杀高并发等操作,严禁一窝蜂的过来拥挤,大家排队,一秒钟 N 个,有序进行。
2. HyStrix 案例
2.1 构建
① 新建cloud-provider-hystrix-payment8001
② POM
<dependencies>
<!--hystrix-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
<!--eureka-client-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<!--本项目的 common 模块-->
<dependency>
<groupId>com.janet.springcloud</groupId>
<artifactId>cloud-api-commons</artifactId>
<version>${project.version}</version>
</dependency>
<!--web启动器 和下面的监控几乎同时出现-->
<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.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<!--lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.18</version>
<optional>true</optional>
</dependency>
<!--SpringBoot测试-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
③ YML
server:
port: 8001
spring:
application:
name: cloud-provider-hystrix-payment
eureka:
client:
register-with-eureka: true
fetch-registry: true
service-url:
defaultZone: http://eureka7001.com:7001/eureka #单机
# defaultZone: http://eureka7001.com:7001/eureka,http://eureka7002.com:7002/eureka # 集群
④ 主启动
package com.janet.springcloud;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
/**
* @Description 测试 Hystrix 的主启动类
* @Date 2020/5/6
* @Author Janet
*/
@SpringBootApplication
@EnableEurekaClient //注册进 Eureka
public class PaymentHystrixMain8001 {
public static void main(String[] args) {
SpringApplication.run(PaymentHystrixMain8001.class, args);
}
}
⑤ 业务类
service
package com.janet.springcloud.service;
import org.springframework.stereotype.Service;
import java.util.concurrent.TimeUnit;
/**
* TODO 这里为了更快捷调试 Hystrix,先不写接口了,直接写 Service 类
* @Description 这个类为了调试 Hystrix,模拟两个方法,一个正常的,一个错误的
* @Date 2020/5/6
* @Author Janet
*/
@Service
public class PaymentService {
/*
* 这个方法是没问题的
* */
public String paymentInfo_OK(Integer id){
return "线程池:"+Thread.currentThread().getName()+"paymentInfo_OK,id:"+id+"\t"+"(*^▽^*)哈哈";
}
/*
* 这个方法是有问题的 ----超时
* */
public String paymentInfo_Timeout(Integer id){
int timeNumber = 3;
try {
TimeUnit.SECONDS.sleep(timeNumber );
} catch (InterruptedException e) {
e.printStackTrace();
}
return "线程池:"+Thread.currentThread().getName()+"paymentInfo_Timeout,id:"+id+"\t"+"┭┮﹏┭┮ 耗时 "+timeNumber+"秒钟";
}
}
controller
package com.janet.springcloud.controller;
import com.janet.springcloud.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
/**
* @Description TODO
* @Date 2020/5/6
* @Author Janet
*/
@RestController
@Slf4j
public class PaymentController {
@Autowired
private PaymentService paymentService;
@Value("${server.port}")
private String serverPort;
//调用没问题的方法
@GetMapping("/payment/hystrix/ok/{id}")
public String paymentInfo_OK(@PathVariable("id") Integer id){
String result = paymentService.paymentInfo_OK(id);
log.info("---------------result:"+ result);
return result;
}
//调用超时的方法
@GetMapping("/payment/hystrix/timeout/{id}")
public String paymentInfo_Timeout(@PathVariable("id") Integer id){
String result = paymentService.paymentInfo_Timeout(id);
log.info("---------------result:"+ result);
return result;
}
}
⑥ 正常测试
启动eureka7001,启动 eureka-provider-hystrix-payment8001。
访问 :
- success的方法: http://localhost:8001/payment/hystrix/ok/31
- 每次调用耗费3秒钟: http://localhost:8001/payment/hystrix/timeout/31
上述 module 均OK,以上述为根基平台,从正确 -> 错误 -> 降级熔断 -> 恢复。
2.2 高并发测试
2.2.1 Jmeter压测测试
开启 Jmeter,来 20000 个并发压死 8001,20000个请求都去访问 paymentInfo_TimeOut 服务
http://localhost:8001/payment/hystrix/timeout/1
测试开始后两个连接访问都很慢了。
为什么会卡死? tomcat 的默认工作线程数被打满了,没有多余的线程来分解压力和处理。
2.2.2 Jmeter压测结论
上面还只是服务提供者8001自己测试,假如此时外部的消费者80也来访问,那消费者只能干等,最终导致消费端80不满意,服务端8001直接被拖死。
2.2.3 80新建加入
a)新建module:cloud-consumer-feign-hystrix-order80
b)POM
<dependencies>
<!--openfeign-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<!--eureka-client-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<!--本项目的 common 模块-->
<dependency>
<groupId>com.janet.springcloud</groupId>
<artifactId>cloud-api-commons</artifactId>
<version>${project.version}</version>
</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.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<!--lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
</dependencies>
c)YML
server:
port: 80
eureka:
client:
register-with-eureka: false
fetch-registry: true
service-url:
defaultZone: http://eureka7001.com:7001/eureka #单机
d)主启动
package com.janet.springcloud;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.openfeign.EnableFeignClients;
/**
* @Description TODO
* @Date 2020/5/7
* @Author Janet
*/
@SpringBootApplication
@EnableFeignClients //激活 OpenFeign
public class OrderHystrixMain80 {
public static void main(String[] args) {
SpringApplication.run(OrderHystrixMain80.class, args);
}
}
e)业务类
PaymentHystrixService
package com.janet.springcloud.service;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
/**
* @Description 在这个 service 中,可以调用微服务 CLOUD-PROVIDER-HYSTRIX-PAYMENT 中的以下方法
* @Date 2020/5/7
* @Author Janet
*/
@Component
@FeignClient(value = "CLOUD-PROVIDER-HYSTRIX-PAYMENT")
public interface PaymentHystrixService {
@GetMapping("/payment/hystrix/ok/{id}")
public String paymentInfo_OK(@PathVariable("id") Integer id);
@GetMapping("/payment/hystrix/timeout/{id}")
public String paymentInfo_Timeout(@PathVariable("id") Integer id);
}
OrderHytrixController
package com.janet.springcloud.controller;
import com.janet.springcloud.service.PaymentHystrixService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
/**
* @Description TODO
* @Date 2020/5/7
* @Author Janet
*/
@RestController
@Slf4j
public class OrderHytrixController {
@Autowired
private PaymentHystrixService paymentHystrixService;
//调用没问题的方法
@GetMapping("/consumer/payment/hystrix/ok/{id}")
public String paymentInfo_OK(@PathVariable("id") Integer id){
String result = paymentHystrixService.paymentInfo_OK(id);
return result;
}
//调用超时的方法
@GetMapping("/consumer/payment/hystrix/timeout/{id}")
public String paymentInfo_Timeout(@PathVariable("id") Integer id){
String result = paymentHystrixService.paymentInfo_Timeout(id);
return result;
}
}
f)正常测试:http://localhost/consumer/payment/hystrix/ok/32
g)高并发测试:
20000 个线程压 8001,消费者 80 微服务再去访问的 OK 服务 8001。 地址:http://localhost/consumer/payment/hystrix/ok/32
消费者 80 要么转圈圈,要么消费端报超时错误。
2.3 故障、导致现象和结论
8001 同一层次的其他接口被困死,因为 tomcat 线程池里面的工作线程已经被挤占完毕。80 此时调用 8001,客户端访问响应缓慢,转圈圈。
正因为有上述故障或不佳表现,才有降级 / 容错 / 限流等技术诞生。
如何解决?
超时导致服务器变慢(转圈)——超时不再等待
出错(宕机或程序运行出错)——出错要有兜底
解决:
- 对方服务(8001)超时了,调用者(80)不能一直卡死等待,必须有服务降级
- 对方服务(8001) down机了,调用者(80)不能一直卡死等待,必须有服务降级
- 对方服务(8001) ok,调用者(80)自己有故障或有自我要求(自己的等待时间小于服务提供者)
2.4 服务降级
2.4.1 cloud-provider-hystrix-payment8001先从自身找问题
设置自身调用超时时间的峰值,峰值内可以正常运行, 超过了需要有兜底的方法处理,做服务降级 fallback。
2.4.2 cloud-provider-hystrix-payment8001 fallback
① 业务类启用:
@HystrixCommand 报异常后如何处理?
一旦调用服务方法失败并抛出了错误信息后,会自动调用 @HystrixCommand 标注好的 fallbckMethod 调用类中的指定方法
package com.janet.springcloud.service;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.stereotype.Service;
import java.util.concurrent.TimeUnit;
/**
* TODO 这里为了更快捷调试 Hystrix,先不写接口了,直接写 Service 类
* @Description 这个类为了调试 Hystrix,模拟两个方法,一个正常的,一个错误的
* @Date 2020/5/6
* @Author Janet
*/
@Service
public class PaymentService {
/*
* 这个方法是没问题的
* */
public String paymentInfo_OK(Integer id){
return "线程池:"+Thread.currentThread().getName()+"paymentInfo_OK,id:"+id+"\t"+"(*^▽^*)哈哈";
}
/*
* 这个方法是有问题的 ----超时
* */
@HystrixCommand(fallbackMethod = "payment_TimeOutHandler", commandProperties = {
@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "3000")
})
public String paymentInfo_Timeout(Integer id){
// 故意制造超时,看看是否会降级,走下面的方法
int timeNumber = 5;
// int age = 10 / 0;
try {
TimeUnit.SECONDS.sleep(timeNumber);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "线程池:"+Thread.currentThread().getName()+"paymentInfo_Timeout,id:"+id+"\t"+"(*^▽^*) 耗时 "+timeNumber+"秒钟";
}
/*
* 这是一个给 paymentInfo_Timeout 方法做服务降级的方法
* */
public String payment_TimeOutHandler(Integer id){
return "线程池:"+Thread.currentThread().getName()+"系统繁忙或运行错误,请稍后再试,id:"+id+"\t"+"┭┮﹏┭┮ ";
}
}
② 主启动类激活:@EnableCircuitBreaker
package com.janet.springcloud;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
/**
* @Description 测试 Hystrix 的主启动类
* @Date 2020/5/6
* @Author Janet
*/
@SpringBootApplication
@EnableEurekaClient //注册进 Eureka
@EnableCircuitBreaker // 激活Hystrix服务降级
public class PaymentHystrixMain8001 {
public static void main(String[] args) {
SpringApplication.run(PaymentHystrixMain8001.class, args);
}
}
③ 测试:
在上述方法中,故意制造了两个异常:
- 我们能接受 3 秒钟,让它运行 5 秒钟,超时异常;
- int age = 10 / 0;
当前服务不可用了,做服务降级,兜底的方案都是 payment_TimeOutHandler
2.4.3 cloud-consumer-feign-hystrix-order80 fallback
80 订单微服务,也可以更好的保护自己,进行客户端端降级保护。(我们自己配置过的热部署方式对 Java 代码的改动明显,但对@HystrixCommand 内属性的修改建议重启微服务)
① POM
<!--hystrix-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
② YML
server:
port: 80
eureka:
client:
register-with-eureka: false
fetch-registry: true
service-url:
defaultZone: http://eureka7001.com:7001/eureka #单机
feign:
hystrix:
enabled: true
③ 主启动:@EnableHystrix
④ 业务类
package com.janet.springcloud.controller;
import com.janet.springcloud.service.PaymentHystrixService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
/**
* @Description TODO
* @Date 2020/5/7
* @Author Janet
*/
@RestController
@Slf4j
public class OrderHytrixController {
@Autowired
private PaymentHystrixService paymentHystrixService;
//调用没问题的方法
@GetMapping("/consumer/payment/hystrix/ok/{id}")
public String paymentInfo_OK(@PathVariable("id") Integer id){
String result = paymentHystrixService.paymentInfo_OK(id);
return result;
}
//调用超时的方法
@GetMapping("/consumer/payment/hystrix/timeout/{id}")
@HystrixCommand(fallbackMethod = "paymentTimeOutFallbackMethod", commandProperties = {
@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "1500")
})
public String paymentInfo_Timeout(@PathVariable("id") Integer id){
int age = 10 /0;
return paymentHystrixService.paymentInfo_Timeout(id);
}
public String paymentTimeOutFallbackMethod(@PathVariable("id") Integer id) {
return "我是消费者80,对方支付系统繁忙请10秒种后再试或者自己运行出错请检查自己,o(╥﹏╥)o";
}
}
2.4.4 目前存在问题
每个业务方法对应一个兜底的方法,代码膨胀。
2.4.5 解决方案
① 每个方法配置一个兜底的方法,代码膨胀。
feign接口系列:@DefaultProperties(defaultFallback="")
每个方法配置一个服务降级方法,实际上是不合理的。除了个别重要核心业务有专属,其他普通的可以通过@DefaultProperties(defaultFallback="")跳转到统一处理结果页面。通用的和独享的分开,避免了代码膨胀,合理减少了代码量。
controller配置:
package com.janet.springcloud.controller;
import com.janet.springcloud.service.PaymentHystrixService;
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 lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
/**
* @Description TODO
* @Date 2020/5/7
* @Author Janet
*/
@RestController
@Slf4j
@DefaultProperties(defaultFallback = "payment_Global_FallbackMethod")
public class OrderHytrixController {
@Autowired
private PaymentHystrixService paymentHystrixService;
//调用没问题的方法
@GetMapping("/consumer/payment/hystrix/ok/{id}")
public String paymentInfo_OK(@PathVariable("id") Integer id){
String result = paymentHystrixService.paymentInfo_OK(id);
return result;
}
//调用超时的方法
@GetMapping("/consumer/payment/hystrix/timeout/{id}")
// @HystrixCommand(fallbackMethod = "paymentTimeOutFallbackMethod", commandProperties = {
// @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "1500")
// })
@HystrixCommand
public String paymentInfo_Timeout(@PathVariable("id") Integer id){
int age = 10 /0;
return paymentHystrixService.paymentInfo_Timeout(id);
}
public String paymentTimeOutFallbackMethod(@PathVariable("id") Integer id) {
return "我是消费者80,对方支付系统繁忙请10秒种后再试或者自己运行出错请检查自己,o(╥﹏╥)o";
}
/**
* 全局fallback
*/
public String payment_Global_FallbackMethod() {
return "Global异常处理信息,请稍后重试.o(╥﹏╥)o";
}
}
② 和业务逻辑混在一起,代码混乱
服务降级,客户端去调用服务端,碰上服务端宕机或关闭。本次案例服务降级处理是在客户端 80 实现完成,与服务端 8001 没有关系,只需要为 Feign 客户端定义的接口添加一个服务降级处理的实现类即可实现解耦。
未来我们要面对的异常:
- 运行
- 超时
- 宕机
OrderHytrixController 中的方法没做任何处理:
a)修改 cloud-consumer-feign-hystrix-order80:根据 cloud-consumer-feign-hystrix-order80 已经有的 PaymentHystrixService 接口,重新新建一个类(PaymentFallbackService)实现接口PaymentFeginService,统一为接口里面的方法进行异常处理。
b)YML(之前已经打开过了)
c)PaymentHystrixService 接口
package com.janet.springcloud.service;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
/**
* @Description 此接口调用微服务 CLOUD-PROVIDER-HYSTRIX-PAYMENT 中的以下方法,服务降级方法在 PaymentFallbackService 类中
* @Date 2020/5/7
* @Author Janet
*/
@Component
@FeignClient(value = "CLOUD-PROVIDER-HYSTRIX-PAYMENT",fallback = PaymentFallbackService.class)
public interface PaymentHystrixService {
@GetMapping("/payment/hystrix/ok/{id}")
public String paymentInfo_OK(@PathVariable("id") Integer id);
@GetMapping("/payment/hystrix/timeout/{id}")
public String paymentInfo_Timeout(@PathVariable("id") Integer id);
}
d)测试
单个eureka先启动7001,PaymentHystrixMain8001启动,正常访问测试:http://localhost/consumer/payment/hystrix/ok/1
故意关闭微服务8001,客户端自己调用
此时服务端 8001 provider 已经 down了,但是我们做了服务降级处理, 让客户端在服务端不可用时也会获得提示信息而不会挂起耗死服务器。
2.5 服务熔断
2.5.1 服务熔断简介
熔断机制是应对雪崩效应的一种微服务链路保护机制,当扇出链路的某个微服务出错不可用或者响应时间太长时,会进行服务的降级,进而熔断该节点微服务的调用,快速返回错误的响应信息。
当检测到该节点的微服务调用响应正常后,恢复调用链路。
在 Spring Cloud 框架里,熔断机制通过 Hystrix 实现。Hystrix 会监控微服务间调用的状况,当失败的调用到一定阈值,缺省是 5 秒内 20 次调用失败,就会启动熔断机制。熔断机制的注解是 @HystrixCommand
2.5.2 实操
修改cloud-provider-hystrix-payment 8001
① PaymentService
package com.janet.springcloud.service;
import cn.hutool.core.util.IdUtil;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;
import java.util.concurrent.TimeUnit;
/**
* TODO 这里为了更快捷调试 Hystrix,先不写接口了,直接写 Service 类
* @Description 这个类为了调试 Hystrix,模拟两个方法,一个正常的,一个错误的
* @Date 2020/5/6
* @Author Janet
*/
@Service
public class PaymentService {
/*
* 这个方法是没问题的
* */
public String paymentInfo_OK(Integer id){
return "线程池:"+Thread.currentThread().getName()+"paymentInfo_OK,id:"+id+"\t"+"(*^▽^*)哈哈";
}
/*
* 这个方法是有问题的 ----超时
* */
@HystrixCommand(fallbackMethod = "payment_TimeOutHandler", commandProperties = {
@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "5000")
})
public String paymentInfo_Timeout(Integer id){
// 故意制造超时,看看是否会降级,走下面的方法
int timeNumber = 3;
// int age = 10 / 0;
try {
TimeUnit.SECONDS.sleep(timeNumber);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "线程池:"+Thread.currentThread().getName()+"paymentInfo_Timeout,id:"+id+"\t"+"(*^▽^*) 耗时 "+timeNumber+"秒钟";
}
/*
* 这是一个给 paymentInfo_Timeout 方法做服务降级的方法
* */
public String payment_TimeOutHandler(Integer id){
return "线程池:"+Thread.currentThread().getName()+"系统繁忙或运行错误,请稍后再试,id:"+id+"\t"+"┭┮﹏┭┮ ";
}
/*
* 上面是服务降级,以下测试服务熔断------------------------------------------------------------------------------------
* */
@HystrixCommand(fallbackMethod = "paymentCircuitBreaker_fallback",commandProperties = {
@HystrixProperty(name = "circuitBreaker.enabled",value = "true"), //是否开启断路器
@HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "10"), //请求次数
@HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "10000"), //时间窗口期
@HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "60") //失败率达到多少后跳闸
})
public String paymentCircuitBreaker(@PathVariable("id") Integer id){
if(id < 0)
throw new RuntimeException("-----------id 不能为负数");
String serialNumber = IdUtil.simpleUUID();
return Thread.currentThread().getName()+ "\t" + "调用成功,流水号"+serialNumber;
}
public String paymentCircuitBreaker_fallback(@PathVariable("id") Integer id){
return "id 不能为负数,请稍后再试,id:"+id;
}
}
为什么设置这些参数
② PaymentController
package com.janet.springcloud.controller;
import com.janet.springcloud.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
/**
* @Description TODO
* @Date 2020/5/6
* @Author Janet
*/
@RestController
@Slf4j
public class PaymentController {
@Autowired
private PaymentService paymentService;
@Value("${server.port}")
private String serverPort;
//调用没问题的方法
@GetMapping("/payment/hystrix/ok/{id}")
public String paymentInfo_OK(@PathVariable("id") Integer id){
String result = paymentService.paymentInfo_OK(id);
log.info("---------------result:"+ result);
return result;
}
//调用超时的方法
@GetMapping("/payment/hystrix/timeout/{id}")
public String paymentInfo_Timeout(@PathVariable("id") Integer id){
String result = paymentService.paymentInfo_Timeout(id);
log.info("---------------result:"+ result);
return result;
}
/*
* 服务熔断--------------------------
* */
@GetMapping("/payment/circuit/{id}")
public String paymentCircuitBreaker(@PathVariable("id") Integer id){
String result = paymentService.paymentCircuitBreaker(id);
log.info("result-----------"+result);
return result;
}
}
③ 自测cloud-provider-hystrix-payment8001
正确: http://localhost:8001/payment/circuit/1
错误:http://localhost:8001/payment/circuit/-31
如果一直用负数测试,错误率上升(这里设置的是 60%)之后,服务熔断,就算是正数正确的也不能正常访问了。然后再测试,多次正确,正确率上升以后慢慢就可以正常访问了。
2.5.3 原理
① 结论
② 熔断类型
- 熔断打开:请求不再调用当前服务,内部设置一般为MTTR (平均故障处理时间),当打开长达导所设时钟则进入半熔断状态。
- 熔断关闭:熔断关闭后不会对服务进行熔断
- 熔断半开:部分请求根据规则调用当前服务,如果请求成功且符合规则则认为当前服务恢复正常,关闭熔断
③ 官网断路器流程图
a)官网步骤:
b)断路器在什么情况下开始起作用
涉及到断路器的三个重要参数:快照时间窗、请求总数阀值、错误百分比阀值。
- 快照时间窗:断路器确定是否打开需要统计一些请求和错误数据,而统计的时间范围就是快照时间窗,默认为最近的 10 秒。
- 请求总数阀值:在快照时间窗内,必须满足请求总数阀值才有资格熔断。默认为 20,意味着在 10 秒内,如果该 hystrix 命令的调用次数不足20次,即使所有的请求都超时或其他原因失败,断路器都不会打开。
- 错误百分比阀值:当请求总数在快照时间窗内超过了阀值,比如发生了 30 次调用,如果在这 30 次调用中,有 15 次发生了超时异常,也就是超过 50% 的错误百分比,在默认设定 50% 阀值情况下,这时候就会将断路器打开。
c)断路器开启或者关闭的条件
- 当满足一定的阈值的时候(默认10秒钟超过20个请求次数)
- 当失败率达到一定的时候(默认10秒内超过50%的请求次数)
- 到达以上阈值,断路器将会开启
- 当开启的时候,所有请求都不会进行转发
- 一段时间之后(默认5秒),这个时候断路器是半开状态,会让其他一个请求进行转发。如果成功,断路器会关闭,若失败,继续开启,重复 4 和 5。
d)断路器打开之后
- 再有请求调用的时候,将不会调用主逻辑,而是直接调用降级 fallback。通过断路器,实现了自动地发现错误并将降级逻辑切换为主逻辑,减少响应延迟的效果。
- 原来的主逻辑要如何恢复呢?
对于这一问题,hystrix 也为我们实现了 自动恢复功能。当断路器打开,对主逻辑进行熔断之后,hystrix 会启动一 个休眠时间窗,在这个时间窗内,降级逻辑是临时的成为主逻辑,当休眠时间窗到期,断路器将进入半开状态,释放一次请求到原来的主逻辑上,如果此次请求正常返回,那么断路器将继续闭合,主逻辑恢复,如果这次请求依然有问题,断路器继续进入打开状态,休眠时间窗重新计时。
e)ALl配置
2.6 服务限流
待续--
3. HyStrix 工作流程
3.1 官网:https://github.com/Netflix/Hystrix/wiki/How-it-Works
3.2 官网图例
3.3 步骤说明
- Construct a HystrixCommand or HystrixObservableCommand Object
- Execute the Command
- Is the Response Cached?
- Is the Circuit Open?
- Is the Thread Pool/Queue/Semaphore Full?
- HystrixObservableCommand.construct() or HystrixCommand.run()
- Calculate Circuit Health
- Get the Fallback
- Return the Successful Response
4. 服务监控 HystrixDashboard
4.1 概述
除了隔离依赖服务的调用以外,Hystrix 还提供 了准实时的调用监控(Hystrix Dashboard) 。Hystrix 会持续地记录所有通过 Hystrix 发起的请求的执行信息,并以统计报表和图形的形式展示给用户,包括每秒执行多少请求多少成功,多少失败等。Netflix 通过 hystrix-metrics- event-stream 项目实现了对以上指标的监控。Spring Cloud 也提供了 Hystrix Dashboard 的整合,对监控内容转化成可视化界面。
4.2 仪表盘9001
① 新建cloud-consumer-hystrix-dashboard9001
② POM
<dependencies>
<!--hystrix dashboard-->
<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-actuator</artifactId>
</dependency>
<!--热部署-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
③ YML
server:
port: 9001
④ HystrixDashboardMain9001 +新注解@EnableHystrixDashboard
package com.janet.springcloud;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.hystrix.dashboard.EnableHystrixDashboard;
/**
* @author Janet
* @date 2020/5/10
*/
@SpringBootApplication
@EnableHystrixDashboard
public class HystrixDashboardMain9001 {
public static void main(String[] args) {
SpringApplication.run(HystrixDashboardMain9001.class);
}
}
⑤ 所有 Provider 微服务提供类 (8001/8002/8003) 都需要监控依赖部署
⑥ 启动 cloud-consumer-hystrix-dashboard9001该微服务后续将监控微服务8001:http://localhost:9001/hystrix
4.3 断路器演示(服务监控hystrixDashboard)
① 修改cloud-provider-hystrix-payment8001
注意:新版本 Hystrix 需要在主启动 MainAppHystrix8001 中指定监控路径,不然会有错误:Unable to connect to Command Metric Stream.
package com.janet.springcloud;
import com.netflix.hystrix.contrib.metrics.eventstream.HystrixMetricsStreamServlet;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.context.annotation.Bean;
/**
* @Description 测试 Hystrix 的主启动类
* @Date 2020/5/6
* @Author Janet
*/
@SpringBootApplication
@EnableEurekaClient //注册进 Eureka
@EnableCircuitBreaker //激活Hystrix服务降级
public class PaymentHystrixMain8001 {
public static void main(String[] args) {
SpringApplication.run(PaymentHystrixMain8001.class, args);
}
/**
* 此配置是为了服务监控而配置,与服务容错本身无观,springCloud 升级之后的坑
* ServletRegistrationBean因为springboot的默认路径不是 /hystrix.stream
* 只要在自己的项目中配置上下面的servlet即可
* @return
*/
@Bean
public ServletRegistrationBean getServlet(){
HystrixMetricsStreamServlet streamServlet = new HystrixMetricsStreamServlet();
ServletRegistrationBean<HystrixMetricsStreamServlet> registrationBean = new ServletRegistrationBean<>(streamServlet);
registrationBean.setLoadOnStartup(1);
registrationBean.addUrlMappings("/hystrix.stream");
registrationBean.setName("HystrixMetricsStreamServlet");
return registrationBean;
}
}
② 监控测试
a)启动一个 eureka 或者 3 个 eureka 集群均可
b)观察监控窗口
- 9001监控8001,填写监控地址:http://localhost:8001/hystrix.stream
- 测试地址
http://localhost:8001/payment/circuit/31
http://localhost:8001/payment/circuit/-31
先访问正确地址,再访问错误地址,再正确地址,会发现图标断路器都是慢慢放开的。
监控结果,成功
监控结果,失败
- 如何看?
7色
1圈
实心圆:共两种含义。它通过颜色的变化代表了实例的健康程度,它的健康度从绿色<黄色<橙色<红色递减。该实心圆除了颜色的变化以外,它的大小也会根据实例的请求流量发生变化,流量越大该实心圆就越大。所以通过该实心圆的展示,就可以在大量的实例中快速的发现故障实例和高压力实例。
1线
曲线:用来记录 2 分钟内流量的相对变化,可以通过它来观察到流量的上升和下降趋势。
整图说明