框架 | 版本 |
---|---|
Idea | 2019.2 |
JDK | 1.8 |
SpringBoot | 2.1.6.RELEASE |
SpringCloud | Greenwich.SR2 |
类似保险丝,为了防止整个系统故障,保护子服务和下游服务。
抛弃一些非核心的接口和数据,保留核心数据。
英文翻译豪猪
Netflix的开源项目
github:https://github.com/Netflix/Hystrix
wiki:https://github.com/Netflix/Hystrix/wiki
99.9930 = 99.7% uptime
0.3% of 1 billion requests = 3,000,000 failures
2+ hours downtime/month even if all dependencies have excellent uptime.
假如微服务系统中每个服务的可用性为99.99%
一次请求中会经过30个服务的调用
那么每次请求的可用性为99.7%
1亿次请求中请求失败的次数达到3百万
转换为服务器宕机超过两小时
这就是Hystrix的重要性
使用maven依赖管理,使用最新的springcloud Greenwich.SR2版本
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloudgroupId>
<artifactId>spring-cloud-dependenciesartifactId>
<version>Greenwich.SR2version>
<type>pomtype>
<scope>importscope>
dependency>
dependencies>
dependencyManagement>
feign依赖里面已经有了hystrix但不是和springcloud结合的,没有**@HystrixCommand**注解
所以需要再加入结合后的hystrix依赖
<dependency>
<groupId>org.springframework.cloudgroupId>
<artifactId>spring-cloud-starter-netflix-hystrixartifactId>
dependency>
@EnableCircuitBreaker
也可以使用
@SpringCloudApplication
该注解默认集成了微服务主要组件的启动注解
@SpringBootApplication
@EnableDiscoveryClient
@EnableCircuitBreaker
在可能抛出异常的方法上加上
@HystrixCommand
@HystrixCommand(fallbackMethod = "testFail")
public Object test(int user){
return null;
}
// 方法名指定 业务方法出现异常则会进入指定的fallbackMethod
public Object testFail(int user){
// 封装errMsg
return null;
}
# application.yml
feign:
hystrix:
enabled: true
fallback指向的必须是实现Feign调用的接口类的实现类
@FeignClient(name = "TEST-SERVER",fallback = TestServiceFallBack.class)
public interface TestService {
}
// 实现类
@Component // 交给spring管理
public class TestServiceFallBack implements TestService{
}
在调用服务出现异常时,feign便会执行fallback指定类的对应方法。可以进行日志记录,短信通知维护人员等。
建议写入消息队列等待消费,或者写入线程异步执行,提高性能。
Hystrix相关配置在
com.netflix.hystrix.HystrixCommandProperties
默认配置feign调用超过一秒认为访问超时
可以在**@HystrixCmomand**中配置
注解中的配置不需要加hystrix前缀,name就为HystrixCommandProperties中指定的key
@HystrixCommand(fallbackMethod = "testFail",commandProperties ={
@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "2000")
})
@GetMapping("/")
public Object test(int user){
return "success";
}
yml的配置方式需要在key前加hystrix.command.default
hystrix:
command:
defalut:
execution:
isolation:
thread:
timeoutInMilliseconds: 3000
<dependency>
<groupId>org.springframework.cloudgroupId>
<artifactId>spring-cloud-starter-netflix-hystrix-dashboardartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-actuatorartifactId>
dependency>
@EnableHystrixDashboard
然后访问项目根路径下的/hystrix
比如:http://localhost:8091/hystrix
然后你会看到
在第一栏中输入项目根目录下路径/actuator/hystrix.stream
比如:http://localhost:8091/actuator/hystrix.stream
其他不用输入,点击Monitor Stream进入监控仪表
如果SpringBoot版本比较高2.x的话进入后会看到这样的页面
因为后面的SpringBoot版本默认关闭了监控断点
配置中开启监控断点:
# 开启监控断点
management:
endpoints:
web:
exposure:
include: "*"
配置好后开启服务
然后请求服务的任意一个接口,监控器便可以正常访问
打断一下!
这个DashBoard监视仪表是使用SSE后台推送技术返回的,flux流式返回!