SpringCloud微服务架构高可用设计方案
SpringCloud微服务架构高可用设计方案
1. 整体架构设计
1.1 多层架构设计
-
接入层
- Nginx负载均衡
- CDN加速
- DDoS防护
- WAF防火墙
-
网关层
- Gateway集群部署
- 请求路由
- 统一鉴权
- 限流熔断
- 协议转换
-
服务层
- 服务注册发现
- 负载均衡
- 服务熔断
- 服务降级
- 服务监控
-
数据层
- 数据库集群
- 缓存集群
- 消息队列集群
- 分布式存储
1.2 核心组件高可用配置
1.2.1 注册中心(Nacos)配置
1.2.2 配置中心高可用
1.2.3 网关高可用配置
2. 服务高可用设计
2.1 服务容错机制
2.1.1 Hystrix熔断配置
@Service
public class UserService {
@HystrixCommand(
fallbackMethod = "getUserFallback",
commandProperties = {
// 熔断器开关
@HystrixProperty(name = "circuitBreaker.enabled", value = "true"),
// 请求量阈值
@HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "20"),
// 错误比例阈值
@HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "50"),
// 熔断时间窗口
@HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "5000"),
// 执行超时时间
@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "1000")
},
threadPoolProperties = {
// 核心线程数
@HystrixProperty(name = "coreSize", value = "30"),
// 最大队列大小
@HystrixProperty(name = "maxQueueSize", value = "100"),
// 队列拒绝阈值
@HystrixProperty(name = "queueSizeRejectionThreshold", value = "100")
}
)
public User getUser(Long id) {
return userMapper.selectById(id);
}
public User getUserFallback(Long id) {
// 返回默认用户或缓存数据
return new User();
}
}
2.2 限流保护
@Configuration
public class SentinelConfig {
@PostConstruct
public void init() {
// 流控规则
List<FlowRule> rules = new ArrayList<>();
// QPS限流
FlowRule qpsRule = new FlowRule();
qpsRule.setResource("getUserById");
qpsRule.setGrade(RuleConstant.FLOW_GRADE_QPS);
qpsRule.setCount(100);
// 预热模式
qpsRule.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_WARM_UP);
qpsRule.setWarmUpPeriodSec(10);
// 并发线程数限流
FlowRule threadRule = new FlowRule();
threadRule.setResource("getUserById");
threadRule.setGrade(RuleConstant.FLOW_GRADE_THREAD);
threadRule.setCount(50);
rules.add(qpsRule);
rules.add(threadRule);
FlowRuleManager.loadRules(rules);
// 熔断降级规则
List<DegradeRule> degradeRules = new ArrayList<>();
DegradeRule degradeRule = new DegradeRule();
degradeRule.setResource("getUserById");
degradeRule.setGrade(RuleConstant.DEGRADE_GRADE_RT);
degradeRule.setCount(100);
degradeRule.setTimeWindow(10);
degradeRules.add(degradeRule);
DegradeRuleManager.loadRules(degradeRules);
}
}