67,628
社区成员




前置内容
(1)、微服务理论入门和手把手带你进行微服务环境搭建及支付、订单业务编写
(2)、SpringCloud之Eureka服务注册与发现
(3)、SpringCloud之Zookeeper进行服务注册与发现
(4)、SpringCloud之Consul进行服务注册与发现
(5)、SpringCloud之Ribbon进行服务调用
(6)、SpringCloud之OpenFeign进行服务调用
1. 服务雪崩
A
调用微服务B
和微服务C
,微服务B
和微服务C
又调用其他的微服务,这就是所谓的扇出。如果扇出的链路上某个微服务的调用响应时间过长或者不可用,对微服务A
的调用就会占用越来越多的资源系统,进而引起系统崩溃,所谓的雪崩效应。Hystrix
是一个用于处理分布式系统的延迟和容错的开源库,在分布式系统里,许多依赖不可避免地会调用失败,比如超时、异常等,Hystrix
能够保证在一个依赖出问题的情况下,不会导致整体微服务失败,避免级联故障,以提高分布式系统的弹性。目前已经处于
停更状态
,但我们需要学习其中相同的理念。
1. 服务降级
fallback
,就是会有一个兜底的方案。触发降级的情况
2. 服务熔断
3. 服务限流
N
个,有序进行。1. 建Module
Module
的名称为cloud-provider-hystrix-payment8001
。2. 改POM
<?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>cloud02</artifactId>
<groupId>com.xiao</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>cloud-provider-hystrix-payment8001</artifactId>
<dependencies>
<!--新增hystrix-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>com.xiao</groupId>
<artifactId>cloud-api-commons</artifactId>
<version>1.0-SNAPSHOT</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>
<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>
</project>
3. 改YML
server:
port: 8001
eureka:
client:
register-with-eureka: true #表识不向注册中心注册自己
fetch-registry: true #表示自己就是注册中心,职责是维护服务实例,并不需要去检索服务
service-url:
# defaultZone: http://eureka7002.com:7002/eureka/ #设置与eureka server交互的地址查询服务和注册服务都需要依赖这个地址
defaultZone: http://eureka7001.com:7001/eureka/
# server:
# enable-self-preservation: false
spring:
application:
name: cloud-provider-hystrix-payment
# eviction-interval-timer-in-ms: 2000
4. 主启动
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
@SpringBootApplication
@EnableEurekaClient
public class PaymentHystrixMain8001 {
public static void main(String[] args) {
SpringApplication.run(PaymentHystrixMain8001.class,args);
}
}
5. PaymentService类
import org.springframework.stereotype.Service;
import java.util.concurrent.TimeUnit;
@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 (Exception e) {e.printStackTrace();}
return "线程池:"+Thread.currentThread().getName()+" paymentInfo_TimeOut,id: "+id+"\t"+"呜呜呜"+" 耗时(秒)"+timeNumber;
}
}
6. PaymentController类
import com.xiao.cloud.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
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;
import javax.annotation.Resource;
@RestController
@Slf4j
public class PaymentController {
@Resource
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;
}
}
7. 测试结果
(1)、注册中心查看
(2)、URL访问查看
8. 高并发压力测试
3
秒的URL
发送20000
个请求的时候,那么会发现两个URL
请求都会需要一定的时间进行响应。(1)、导致这样的原因
URL
-- http://localhost:8001/payment/hystrix/timeout/1
,那么tomcat
的线程大多数去处理那些大量的URL请求 http://localhost:8001/payment/hystrix/timeout/1
,那么如果我们再去请求http://localhost:8001/payment/hystrix/ok/1
,那么就需要等待一定的时间了。1. 建Module
Module
的名称为cloud-consumer-feign-hystrix-order80
。2. 改POM
<dependencies>
<!--新增hystrix-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>com.xiao</groupId>
<artifactId>cloud-api-commons</artifactId>
<version>1.0-SNAPSHOT</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>
<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>
3. 改YML
server:
port: 80
eureka:
client:
register-with-eureka: false #表识不向注册中心注册自己
service-url:
defaultZone: http://eureka7001.com:7001/eureka/
4. 主启动
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.openfeign.EnableFeignClients;
@SpringBootApplication
@EnableFeignClients
public class OrderHystrixMain80 {
public static void main(String[] args) {
SpringApplication.run(OrderHystrixMain80.class,args);
}
}
5. PaymentHystrixService类
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;
@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);
}
6. OrderHystrixController类
import com.xiao.cloud.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;
@RestController
@Slf4j
public class OrderHystrixController {
@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;
}
}
7. 高并发测试结果
1. 解决要求
2. 解决办法
8001
)超时了,调用者(80
)不能一直卡死等待,必须有服务降级。8001
)down机了,调用者(80
)不能一直卡死等待,必须有服务降级。8001
)OK,调用者(80
)自己出故障或有自我要求(自己的等待时间小于服务提供者),自己处理降级1. 修改PaymentService
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;
@Service
public class PaymentService {
public String paymentInfo_OK(Integer id){
return "线程池:"+Thread.currentThread().getName()+" paymentInfo_OK,id: "+id+"\t"+"哈哈哈" ;
}
//失败
@HystrixCommand(fallbackMethod = "paymentInfo_TimeOutHandler" ,commandProperties = {
@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "3000") //3秒钟以内就是正常的业务逻辑
})
public String paymentInfo_TimeOut(Integer id){
int timeNumber = 5;
try { TimeUnit.SECONDS.sleep(timeNumber); }catch (Exception e) {e.printStackTrace();}
return "线程池:"+Thread.currentThread().getName()+" paymentInfo_TimeOut,id: "+id+"\t"+"呜呜呜"+" 耗时(秒)"+timeNumber;
}
public String paymentInfo_TimeOutHandler(Integer id){
return "线程池:"+Thread.currentThread().getName()+"系统超时或者服务繁忙,请稍后重试 paymentInfo_TimeOutHandler,id: "+id+"\t"+"/(ㄒoㄒ)/~~";
}
}
2. 在主启动类上添加以下注解
@EnableCircuitBreaker
开启其相应的全局配置。3. 测试结果
1. 在yml文件中添加以下代码
feign:
hystrix:
enabled: true #如果处理自身的容错就开启。开启方式与生产端不一样。
2. 在主启动类上添加以下注解
@EnableHystrix
。3. 在OrderHystrixController类中添加以下代码
@GetMapping("/consumer/payment/hystrix/timeout/{id}")
@HystrixCommand(fallbackMethod = "paymentTimeOutFallbackMethod",commandProperties = {
@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "1500") //3秒钟以内就是正常的业务逻辑
})
public String paymentInfo_TimeOut(@PathVariable("id") Integer id){
String result = paymentHystrixService.paymentInfo_TimeOut(id);
return result;
}
//兜底方法
public String paymentTimeOutFallbackMethod(@PathVariable("id") Integer id){
return "我是消费者80,对付支付系统繁忙请10秒钟后再试或者自己运行出错请检查自己,(┬_┬)";
}
4. 测试结果
1. 目前的问题
2. 解决办法
(1)、解决代码膨胀问题
1. 将OrderHystrixController
类的代码修改为以下
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 com.xiao.cloud.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;
@RestController
@Slf4j
@DefaultProperties(defaultFallback = "payment_Global_FallbackMethod")
public class OrderHystrixController {
@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") //3秒钟以内就是正常的业务逻辑
// })
@HystrixCommand
public String paymentInfo_TimeOut(@PathVariable("id") Integer id){
int age = 10 / 0;
String result = paymentHystrixService.paymentInfo_TimeOut(id);
return result;
}
//兜底方法
public String paymentTimeOutFallbackMethod(@PathVariable("id") Integer id){
return "我是消费者80,对付支付系统繁忙请10秒钟后再试或者自己运行出错请检查自己,(┬_┬)";
}
// 全局兜底的方法
public String payment_Global_FallbackMethod(){
return "Global异常处理信息,请稍后再试,(┬_┬)";
}
}
2. 测试结果
fallback
就是该兜底方法。而且需要在使用该兜底方法的上面标注@HystrixCommand
注解。fallback
,那么我们需要进行相关的详细配置,配置参考前面的支付侧和订单侧的配置。(2)、解决代码混乱问题
1. 在订单模块中新建PaymentFallbackService
类实现PaymentFeignClientService
接口
import org.springframework.stereotype.Component;
@Component
public class PaymentFallbackService implements PaymentHystrixService{
@Override
public String paymentInfo_OK(Integer id) {
return "-----PaymentFallbackService fall back-paymentInfo_OK , (┬_┬)";
}
@Override
public String paymentInfo_TimeOut(Integer id) {
return "-----PaymentFallbackService fall back-paymentInfo_TimeOut , (┬_┬)";
}
}
2. 在yml
文件中添加以下代码
feign:
hystrix:
enabled: true #如果处理自身的容错就开启。开启方式与生产端不一样。
3. 在对应的微服务调用接口上添加以下注解
@FeignClient(value = "CLOUD-PROVIDER-HYSTRIX-PAYMENT",fallback = PaymentFallbackService.class)
4. 测试结果
8001
的支付模块down
掉模拟支付微服务模块宕机,会发现当支付微服务模块宕机的时候,那么微服务调用接口会使用其配置的fallback
的并实现该接口的实现类中的方法。SpringCloud
框架里,熔断机制通过Hystrix
实现。Hystrix
会监控微服务间调用的状况,当失败的调用达到一定阈值,就会启动熔断机制。熔断机制的注解实@HystrixCommand
。1. 修改cloud-provider-hystrix-payment8001 的 PaymentService类
//服务熔断
@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;
}
requestVolumeThreshold
为10
,表示只有请求次数超过10
次之后才有资格发生服务熔断;errorThresholdPercentage
为60
,表示的是当我们出现错误的概率超过60%
的时候,它就会出现服务熔断;如果错误的概率低于60%
的时候,那么就会慢慢恢复调用链路;sleepWindowInMilliseconds
为10000
表示当出现熔断现象之后10
秒会进行恢复调用链路的尝试。2. 修改cloud-provider-hystrix-payment8001 的 PaymentController类
//===服务熔断
@GetMapping("/payment/circuit/{id}")
public String paymentCircuitBreaker(@PathVariable("id") Integer id){
String result = paymentService.paymentCircuitBreaker(id);
log.info("*******result:"+result);
return result;
}
3. 测试结果
id
为正数的时候,但是它返回的还是负数查找出来的结果,所以此时已经出现了服务熔断现象。1. 三个状态说明
fallback
,内部设置时钟一般为MTTR
(平均故障处理时间),当打开时长达到所设时钟则进入熔断状态2. 重要参数说明
requestVolumeThreshold
:当满足一定阀值的时候断路器开启(默认10
秒内超过20
个请求次数)errorThresholdPercentage
:当失败率达到一定的时候断路器开启(默认10
秒内超过50%
请求失败)sleepWindowInMilliseconds
:一段时间之后(默认是5
秒),这个时候断路器是半开状态,会让其中一个请求进行转发。如果成功,断路器会关闭,若失败,继续开启。工作流程
1.每个请求都会封装到 HystrixCommand 中
2.请求会以同步或异步的方式进行调用
3.判断熔断器是否打开,如果打开,它会直接跳转到 8 ,进行降级
4.判断线程池/队列/信号量是否跑满,如果跑满进入降级步骤8
5.如果前面没有错误,就调用 run 方法,运行依赖逻辑
5.运行方法可能会超时,超时后从 5a 到 8,进行降级
6.运行过程中如果发生异常,会从 6b 到 8,进行降级
6.运行正常会进入 6a,正常返回回去,同时把错误或正常调用结果告诉 7 (Calculate Circuit Health)
7.Calculate Circuit Health它是 Hystrix 的大脑,是否进行熔断是它通过错误和成功调用次数计算出来的
8.降级方法(8a没有实现降级、8b实现降级且成功运行、8c实现降级方法,但是出现异常)
8a.没有实现降级方法,直接返回异常信息回去
8b.实现降级方法,且降级方法运行成功,则返回降级后的默认信息回去
8c.实现降级方法,但是降级也可能出现异常,则返回异常信息回去
除了隔离依赖服务的调用以外,Hystrix
还提供了准实时的调用监控,Hystrix
会持续地记录所有通过Hystrix
发起的请求的执行信息,并以统计报表和图形的形式展示给用户,包括每秒执行多少请求多少成功,多少失败等。Netflix
通过hystrix-metrics-event-stream
项目实现了对以上指标的监控。SpringCloud
也提供了Hystrix DashBoard
的整合,对监控内容转化成可视化界面
1. 建Module
Module
的名称为cloud-consumer-hystrix-dashboard9001
。2. 改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>
3. 改YML
server:
port: 9001
4. 主启动
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.hystrix.dashboard.EnableHystrixDashboard;
@SpringBootApplication
@EnableHystrixDashboard
public class HystrixDashboardMain9001 {
public static void main(String[] args) {
SpringApplication.run(HystrixDashboardMain9001.class,args);
}
}
5. 测试结果
1. 被监控方需要引入的依赖
<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>
2. 被监控方主启动类上需要添加的代码
@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;
}
3. 怎样配置9001监控8001
4. 测试结果
http://localhost:8001/payment/circuit/-11
请求的时候,监控图像如图所示。5. 查看的规则说明
(1)、图一
(2)、图二