一、Hystix概述
1.1、简介
Hystrix is a latency and fault tolerance library designed to isolate points of access to remote systems, services and 3rd party libraries, stop cascading failure and enable resilience in complex distributed systems where failure is inevitable.
Hystrix是一个延迟和容错库,旨在隔离对远程系统、服务和第三方库的访问点,停止级联故障,并在不可避免的复杂分布式系统中启用弹性。
GitHub: https://github.com/Netflix/Hystrix/
1.2、Hystix的作用
(1) Latency and Fault Tolerance(延迟和容错)
Stop cascading failures. Fallbacks and graceful degradation. Fail fast and rapid recovery.
Thread and semaphore isolation with circuit breakers.
(2) Realtime Operations(实时操作)
Realtime monitoring and configuration changes. Watch service and property changes take effect immediately as they spread across a fleet.
Be alerted, make decisions, affect change and see results in seconds.
(3) Concurrency(并发)
Parallel execution. Concurrency aware request caching. Automated batching through request collapsing.
1.3、熔断器的工作机制
1.4、服务雪崩效应
详细查看下面的这篇博客
转载:https://blog.youkuaiyun.com/sheinenggaosuwo/article/details/86592893
1.5、Hystrix解决服务雪崩的方法
- 线程隔离
- 服务熔断
二、Hystrix
2.1、引入依赖,服务的消费方作降级处理
<!--引入Hystrix的依赖-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
2.2、在启动类添加注解
-
@EnableCircuitBreaker
-
@EnableHystrix
2.3、application.yaml中配置Hystrix
默认不需要配置,可根据具体需求更改
#配置Hystrix的超时时长
hystrix:
command:
default:
execution:
isolation:
thread:
timeoutInMilliseconds: 3000
2.4、Contriller中做失败降级处理
@GetMapping("{id}")
//添加注解,对服务进行失败降级处理
@HystrixCommand(fallbackMethod = "queryByIdFallback")
public String queryById(@PathVariable("id")int id){
String url = "http://user_service/user/"+id;
String user = restTemplate.getForObject(url, String.class);
return user;
}
public String queryByIdFallback(int id){
return "不好意思,服务器繁忙,请稍后再试!";
}
2.5、类上做统一降级处理
@DefaultProperties(defaultFallback = "defaultFallback")
//在方法上加上@HystrixCommand即可启用默认的降级处理
2.6、服务降级时间控制
@HystrixCommand(
commandProperties = {
@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value="4000")
}
)
2.7、SpringCloudApplication注解说明
package org.springframework.cloud.client;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootApplication
@EnableDiscoveryClient
@EnableCircuitBreaker
public @interface SpringCloudApplication {
}
看源码可知: @EnableCircuitBreaker @EnableDiscoveryClient @SpringBootApplication 等于 @SpringCloudApplication