面试题答案
一键面试对熔断机制的理解
熔断机制是一种应对分布式系统中服务故障的容错策略。当某个服务出现高频率故障时,熔断机制可以防止故障扩散到其他服务,避免整个系统因级联故障而崩溃。它就像电路中的保险丝,当电流过大(服务请求失败率过高)时,保险丝熔断(服务熔断),暂时切断对故障服务的调用,从而保护整个系统的稳定性。一段时间后,熔断机制会尝试半开状态,允许少量请求进入,以检测服务是否恢复正常。
使用Hystrix在Spring Cloud项目中实现熔断的配置步骤和关键代码片段
- 引入依赖
在
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 org.springframework.cloud.netflix.hystrix.EnableHystrix;
@SpringBootApplication
@EnableHystrix
public class YourApplication {
public static void main(String[] args) {
SpringApplication.run(YourApplication.class, args);
}
}
- 创建熔断方法
在需要熔断保护的服务调用方法所在的类中,使用
@HystrixCommand
注解,并指定熔断后的降级方法。例如:
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.stereotype.Service;
@Service
public class YourService {
@HystrixCommand(fallbackMethod = "fallbackMethod")
public String callRemoteService() {
// 这里是正常调用远程服务的代码
return "Remote service response";
}
public String fallbackMethod() {
// 熔断后的降级逻辑,返回兜底数据
return "Fallback response";
}
}
- Hystrix配置
在
application.properties
或application.yml
中可以对Hystrix进行一些配置,例如:
hystrix:
command:
default:
execution:
isolation:
thread:
timeoutInMilliseconds: 2000 # 调用超时时间,单位毫秒
circuitBreaker:
requestVolumeThreshold: 10 # 在滚动时间窗内,至少有10个请求才会触发熔断
sleepWindowInMilliseconds: 5000 # 熔断后多久尝试半开,单位毫秒
errorThresholdPercentage: 50 # 失败率达到50%触发熔断