Spring Cloud Hystrix
- 防雪崩利器
- 基于Netflix对应的Hystrix
- 服务降级
- 依赖隔离
- 服务熔断
- 监控(Hystrix Dashboard)
服务降级
- 优先核心服务,非核心服务不可用或弱可用
- 通过HystrixCommand注解指定
- fallbackMethod(回退函数)中具体实现降级逻辑
一、添加服务容错
1.Finchley.RELEASE添加Maven依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
2.启动类添加注解
@EnableCircuitBreaker
或
@SpringCloudApplication
包含:
@SpringBootApplication
@EnableDiscoveryClient
@EnableCircuitBreaker
3.添加 @HystrixCommand(fallbackMethod = “fallback”)注解
1.指定方法降级
例:
@HystrixCommand(fallbackMethod = "fallback")
@GetMapping("/getProductInfoList")
2.默认降级
例:
@RestController
@DefaultProperties(defaultFallback = "defaultFallback")
在加:
@HystrixCommand
二、超时设置
@HystrixCommand(commandProperties = {
@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "3000")
})
@GetMapping("/getProductInfoList"){
...
}
配置方式实现
- 1.添加注解
@HystrixCommand
- 2.添加配置文件
hystrix:
command:
default:
execution:
isolation:
thread:
timeoutInMilliseconds: 3000
可单独设置指定方法超市时间,例:getProductInfoList
hystrix:
command:
default:
execution:
isolation:
thread:
timeoutInMilliseconds: 1000
getProductInfoList:
execution:
isolation:
thread:
timeoutInMilliseconds: 3000
三、断路器模式-服务熔断
@HystrixCommand(commandProperties = {
@HystrixProperty(name = "circuitBreaker.enabled", value = "true"), // 开启熔断机制
@HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "10"), // 设置当请求失败的数量达到10个后,打开断路器,默认值为20
@HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "10000"), // 设置打开断路器多久以后开始尝试恢复,默认为5s
@HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "60"), // 设置出错百分比阈值,当达到此阈值后,打开断路器,默认50%
})
@GetMapping("/getProductInfoList")
public String getProductInfoList(@RequestParam("number") Integer number){
...
}
四、feign-hystrix的使用
首先打开feign-hystrix
feign:
hystrix:
enabled: true
添加降级回调函数
- ProductClientFallback.class
@FeignClient(name = "product",fallback = ProductClient.ProductClientFallback.class)
public interface ProductClient {
@PostMapping("/product/listForOrder")
List<ProductInfoOutput> listForOrder(@RequestBody List<String> productIdList);
@PostMapping("/product/decreaseStock")
void decreaseStock(@RequestBody List<DecreaseStockInput> decreaseStockInputList);
@Component
static class ProductClientFallback implements ProductClient{
@Override
public List<ProductInfoOutput> listForOrder(List<String> productIdList) {
return null;
}
@Override
public void decreaseStock(List<DecreaseStockInput> decreaseStockInputList) {
}
}
}
五、界面化
1.添加依赖
<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>
2.启动类添加注解
@EnableHystrixDashboard
3.访问hystrix
http://localhost:8081/hystrix
4.单服务监控
有:actuator
http://localhost:8081/hystrix/actuator/hystrix.stream