常见的服务容错机制
- 熔断(Circuit Breaker):当某个服务的失败率达到一定阈值时,熔断器会跳闸,后续请求不再直接调用该服务,而是直接返回一个预设的 fallback 响应,避免长时间等待和大量无效请求。
- 降级(Degradation):当系统资源紧张或某个服务不可用时,主动降低服务的功能或性能,以保证核心功能可用。例如,关闭一些非核心的接口或功能。
- 限流(Rate Limiting):限制对某个服务的请求速率,防止因流量过大导致服务过载。通过限制单位时间内的请求数量,保护服务不被压垮。
- 重试(Retry):当请求失败时,自动重试一定次数,有可能是因为临时的网络波动等原因导致失败,重试可能使请求成功。
使用 Hystrix 实现熔断机制
配置步骤(以 Spring Boot 项目为例)
- 引入依赖:在
pom.xml
文件中添加 Hystrix 依赖。
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
- 启用 Hystrix:在 Spring Boot 主类上添加
@EnableHystrix
注解。
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import com.netflix.hystrix.contrib.javanica.annotation.EnableHystrix;
@SpringBootApplication
@EnableHystrix
public class YourApplication {
public static void main(String[] args) {
SpringApplication.run(YourApplication.class, args);
}
}
- 定义熔断方法:在需要熔断保护的方法所在类上添加
@HystrixCommand
注解,并指定 fallback 方法。
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.stereotype.Service;
@Service
public class YourService {
@HystrixCommand(fallbackMethod = "fallbackMethod")
public String yourMethod() {
// 实际调用其他服务的代码
return "正常响应";
}
public String fallbackMethod() {
// 熔断后的备用响应
return "熔断,返回备用响应";
}
}
关键参数含义
circuitBreaker.requestVolumeThreshold
:在滚动时间窗内,请求数量达到此阈值才会开启熔断检查。默认值是 20,意味着在 10 秒内如果请求数量小于 20,即使所有请求都失败,熔断器也不会开启。
circuitBreaker.errorThresholdPercentage
:当请求失败率达到此百分比时,熔断器会开启。默认值是 50%,即请求失败率超过 50% 时熔断。
circuitBreaker.sleepWindowInMilliseconds
:熔断器开启后,经过此时间窗后会进入半开状态,尝试少量请求。默认值是 5000 毫秒(5 秒)。
execution.isolation.thread.timeoutInMilliseconds
:Hystrix 命令执行的超时时间,默认值是 1000 毫秒(1 秒)。如果执行时间超过此值,命令会被中断并视为失败。