独家秘技:从零到一打造高可用系统
独家秘技:从零到一打造高可用系统
欢迎来到付费专区!本文将为您揭秘高可用系统设计的核心方法论,这些都是经过多年实战验证的宝贵经验。
前言:为什么需要高可用?
在互联网时代,系统的可用性直接关系到:
- 用户体验:系统宕机会导致用户流失
- 业务收入:每分钟的停机都可能造成巨额损失
- 品牌形象:频繁故障会损害用户信任
可用性指标
| 可用性等级 | 年停机时间 | 适用场景 |
|---|---|---|
| 99% | 3.65 天 | 内部系统、非核心业务 |
| 99.9% | 8.76 小时 | 一般互联网产品 |
| 99.99% | 52.6 分钟 | 金融、支付等核心系统 |
| 99.999% | 5.26 分钟 | 电信、医疗等关键基础设施 |
一、高可用设计原则
1.1 冗余原则
核心思想:任何单点都可能故障,必须有备份。
// 示例:多实例部署 + 负载均衡
// 使用 cluster 模块利用多核 CPU
const cluster = require('cluster');
const numCPUs = require('os').cpus().length;
if (cluster.isMaster) {
console.log(`主进程 ${process.pid} 正在运行`);
// 衍生工作进程
for (let i = 0; i < numCPUs; i++) {
cluster.fork();
}
// 监听工作进程退出,自动重启
cluster.on('exit', (worker, code, signal) => {
console.log(`工作进程 ${worker.process.pid} 已退出,正在重启...`);
cluster.fork();
});
} else {
// 工作进程:启动 HTTP 服务
const app = require('./app');
app.listen(3000, () => {
console.log(`工作进程 ${process.pid} 已启动`);
});
}
1.2 故障隔离原则
核心思想:一个组件的故障不能影响整个系统。
// 示例:熔断器模式 (Circuit Breaker)
class CircuitBreaker {
constructor(options = {}) {
this.failureThreshold = options.failureThreshold || 5;
this.resetTimeout = options.resetTimeout || 30000;
this.failureCount = 0;
this.state = 'closed'; // closed, open, half-open
this.lastFailureTime = 0;
}
async execute(fn) {
if (this.state === 'open') {
if (Date.now() - this.lastFailureTime > this.resetTimeout) {
this.state = 'half-open';
} else {
throw new Error('Circuit breaker is open');
}
}
try {
const result = await fn();
this.onSuccess();
return result;
} catch (error) {
this.onFailure();
throw error;
}
}
onSuccess() {
this.failureCount = 0;
this.state = 'closed';
}
onFailure() {
this.failureCount++;
this.lastFailureTime = Date.now();
if (this.failureCount >= this.failureThreshold) {
this.state = 'open';
}
}
}
// 使用示例
const breaker = new CircuitBreaker({ failureThreshold: 3, resetTimeout: 10000 });
async function callExternalService() {
return breaker.execute(async () => {
const response = await fetch('https://external-service.com/api');
return response.json();
});
}
1.3 降级原则
核心思想:在资源不足时,优先保证核心功能。
// 示例:服务降级策略
class DegradationManager {
constructor() {
this.strategies = new Map();
this.enabled = true;
}
registerStrategy(name, checkFn, fallbackFn) {
this.strategies.set(name, { checkFn, fallbackFn });
}
async execute(name, normalFn) {
if (!this.enabled) {
return normalFn();
}
const strategy = this.strategies.get(name);
if (!strategy) {
return normalFn();
}
const shouldDegrade = await strategy.checkFn();
if (shouldDegrade) {
console.warn(`服务降级: ${name}`);
return strategy.fallbackFn();
}
return normalFn();
}
}
// 注册降级策略
const degradation = new DegradationManager();
// 推荐服务降级
degradation.registerStrategy('recommendation',
async () => {
// 检查系统负载,如果过高则降级
const load = process.loadavg()[0];
return load > 2; // CPU 负载过高时降级
},
() => {
// 降级方案:返回热门内容而不是个性化推荐
return getHotRecommendations();
}
);
// 使用
async function getRecommendations(userId) {
return degradation.execute('recommendation', async () => {
return getPersonalizedRecommendations(userId);
});
}