面试题答案
一键面试1. 使用组件
- Hystrix:Netflix开源的库,用于隔离、熔断以及控制服务的延迟和故障。在Spring Cloud中,Spring Cloud Netflix Hystrix对其进行了集成,方便在Spring Boot应用中使用。
- Archaius:同样是Netflix开源的动态配置管理库。结合Hystrix,可以实现动态修改熔断与降级的配置参数。Spring Cloud Config也可以实现配置动态刷新,但Archaius能直接在应用内动态调整一些Hystrix配置。
2. 配置实现灵活调整策略
2.1 引入依赖
在pom.xml
中添加以下依赖:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
<dependency>
<groupId>com.netflix.archaius</groupId>
<artifactId>archaius-core</artifactId>
</dependency>
2.2 启用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);
}
}
2.3 创建熔断与降级方法
使用@HystrixCommand
注解来标记需要熔断与降级的方法,并指定降级方法:
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.stereotype.Service;
@Service
public class YourService {
@HystrixCommand(fallbackMethod = "fallbackMethod")
public String yourBusinessMethod() {
// 调用其他微服务或执行可能失败的业务逻辑
return "正常返回结果";
}
public String fallbackMethod() {
// 降级逻辑,如返回默认值或提示信息
return "服务暂时不可用,请稍后重试";
}
}
2.4 动态调整配置
- 使用Archaius:通过Archaius可以在运行时动态修改Hystrix的配置参数。例如,修改熔断阈值:
import com.netflix.config.DynamicPropertyFactory;
import com.netflix.hystrix.HystrixCommandProperties;
public class DynamicConfig {
public static void main(String[] args) {
DynamicPropertyFactory dynamicPropertyFactory = DynamicPropertyFactory.getInstance();
dynamicPropertyFactory.getDoubleProperty("hystrix.command.YourService.yourBusinessMethod.circuitBreaker.errorThresholdPercentage", 50);
}
}
这里将YourService.yourBusinessMethod
这个Hystrix命令的熔断错误阈值动态修改为50%。
- 使用Spring Cloud Config:将Hystrix的配置放在配置中心(如Git仓库),通过Spring Cloud Config客户端来获取配置。在配置文件中定义Hystrix相关配置:
hystrix:
command:
YourService.yourBusinessMethod:
circuitBreaker:
errorThresholdPercentage: 60
然后通过Spring Cloud Config客户端的配置刷新机制(如@RefreshScope
注解结合Spring Cloud Bus)来动态更新配置。在需要刷新配置的Controller或Service上添加@RefreshScope
:
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RefreshScope
@RestController
public class ConfigRefreshController {
@Value("${hystrix.command.YourService.yourBusinessMethod.circuitBreaker.errorThresholdPercentage}")
private double errorThresholdPercentage;
@GetMapping("/config")
public String getConfig() {
return "当前熔断错误阈值: " + errorThresholdPercentage;
}
}
通过触发Spring Cloud Bus的刷新事件(如发送POST请求到/actuator/bus-refresh
端点),可以动态更新Hystrix的配置参数,实现灵活的调整策略。