🎯 学习目标:性能调优:并发处理、缓存策略、资源优化
⏱️ 阅读时间:约 12 分钟
💡 前置要求:无
⚡ 性能优化三要素
核心方向总览
| 并发处理 | ||
| 缓存策略 | ||
| 资源优化 |
🔄 并发处理
任务队列
classTaskQueue {constructor(concurrency = 5) {this.concurrency = concurrency;this.running = 0;this.queue = []; }asyncadd(task) {returnnewPromise((resolve, reject) => {this.queue.push({ task, resolve, reject });this.process(); }); }asyncprocess() {if (this.running >= this.concurrency || this.queue.length === 0) {return; }this.running++;const { task, resolve, reject } = this.queue.shift();try {const result = awaittask();resolve(result); } catch (error) {reject(error); } finally {this.running--;this.process(); } }}// 使用示例const queue = newTaskQueue(5); // 最多 5 个并发// 批量处理任务const tasks = Array.from({ length: 100 }, (_, i) =>() =>processItem(i));const results = awaitPromise.all(tasks.map(task => queue.add(task)));批量处理
// 批量 API 调用asyncfunctionbatchApiCall(items, batchSize = 10) {const results = [];for (let i = 0; i < items.length; i += batchSize) {const batch = items.slice(i, i + batchSize);const batchResults = awaitPromise.all(batch.map(callApi)); results.push(...batchResults);// 避免速率限制awaitsleep(100); }return results;}// 批量数据库操作asyncfunctionbatchInsert(records, batchSize = 100) {for (let i = 0; i < records.length; i += batchSize) {const batch = records.slice(i, i + batchSize);await db.insertMany(batch); }}流式处理
// 处理大文件asyncfunctionprocessLargeFile(filePath) {const stream = createReadStream(filePath);forawait (const chunk of stream) {awaitprocessChunk(chunk); }}// 流式响应asyncfunctionstreamResponse(request, response) {const stream = awaitgenerateLargeResponse(); response.setHeader('Content-Type', 'application/json');forawait (const chunk of stream) { response.write(chunk); } response.end();}💾 缓存策略
内存缓存
classCache {constructor(defaultTTL = 300) {this.defaultTTL = defaultTTL;this.store = newMap(); }asyncget(key) {const item = this.store.get(key);if (!item) {returnnull; }if (Date.now() > item.expiresAt) {this.store.delete(key);returnnull; }return item.value; }asyncset(key, value, ttl = this.defaultTTL) {this.store.set(key, { value,expiresAt: Date.now() + (ttl * 1000) }); }asyncdelete(key) {this.store.delete(key); }asyncclear() {this.store.clear(); }}// 使用示例const cache = newCache();asyncfunctiongetData(key) {// 先查缓存let data = await cache.get(key);if (data) {return data; }// 缓存未命中,从数据库获取 data = await db.query(key);// 写入缓存await cache.set(key, data, 600); // 10 分钟 TTLreturn data;}多层缓存
classMultiLevelCache {constructor() {// L1: 内存缓存(快,容量小)this.l1 = newCache({ maxSize: '100MB' });// L2: Redis 缓存(较快,容量大)this.l2 = newRedisCache();// L3: 数据库(慢,持久化)this.l3 = newDatabase(); }asyncget(key) {// L1 命中let data = awaitthis.l1.get(key);if (data) return data;// L2 命中 data = awaitthis.l2.get(key);if (data) {awaitthis.l1.set(key, data); // 回填 L1return data; }// L3 获取 data = awaitthis.l3.get(key);if (data) {awaitthis.l2.set(key, data);awaitthis.l1.set(key, data); }return data; }}缓存失效策略
// 定时失效await cache.set(key, value, 3600); // 1 小时后失效// 依赖失效asyncfunctionupdateUser(userId, data) {await db.update(userId, data);// 使相关缓存失效await cache.delete(`user:${userId}`);await cache.delete(`user:${userId}:profile`);await cache.delete(`user:${userId}:settings`);}// 版本失效const cacheVersion = 'v1';await cache.set(`${cacheVersion}:key`, value);// 更新时升级版本const newVersion = 'v2';await cache.set(`${newVersion}:key`, newValue);📊 资源优化
连接池
classConnectionPool {constructor(createConnection, maxSize = 10) {this.createConnection = createConnection;this.maxSize = maxSize;this.connections = [];this.inUse = newSet(); }asyncacquire() {// 有空闲连接if (this.connections.length > 0) {const conn = this.connections.pop();this.inUse.add(conn);return conn; }// 创建新连接if (this.inUse.size < this.maxSize) {const conn = awaitthis.createConnection();this.inUse.add(conn);return conn; }// 等待空闲returnnewPromise(resolve => {this.waitQueue = this.waitQueue || [];this.waitQueue.push(resolve); }); }asyncrelease(conn) {this.inUse.delete(conn);if (this.waitQueue && this.waitQueue.length > 0) {const resolve = this.waitQueue.shift();this.inUse.add(conn);resolve(conn); } else {this.connections.push(conn); } }}// 使用示例const pool = newConnectionPool(() =>createDatabaseConnection(),10);asyncfunctionquery(sql) {const conn = await pool.acquire();try {returnawait conn.query(sql); } finally {await pool.release(conn); }}资源限制
classResourceLimiter {constructor(limits) {this.limits = limits;this.usage = {}; }asyncacquire(resource, amount = 1) {const limit = this.limits[resource];if (!limit) {returntrue; // 无限制 }const current = this.usage[resource] || 0;if (current + amount > limit) {thrownewError(`资源 ${resource} 超限:${current + amount}/${limit}`); }this.usage[resource] = current + amount;returntrue; }release(resource, amount = 1) {this.usage[resource] = (this.usage[resource] || 0) - amount; }}// 使用示例const limiter = newResourceLimiter({memory: 1024 * 1024 * 1024, // 1GBcpu: 4, // 4 核connections: 100});asyncfunctionprocessTask(task) {await limiter.acquire('memory', task.memoryNeeded);await limiter.acquire('cpu', task.cpuNeeded);try {returnawait task.run(); } finally { limiter.release('memory', task.memoryNeeded); limiter.release('cpu', task.cpuNeeded); }}懒加载
// 延迟加载大对象classLazyLoader {constructor(loader) {this.loader = loader;this.instance = null; }asyncget() {if (!this.instance) {this.instance = awaitthis.loader(); }returnthis.instance; }}// 使用示例const largeModel = newLazyLoader(() =>loadMLModel());// 只在需要时加载const result = await (await largeModel.get()).predict(data);📈 性能监控
classPerformanceMonitor {constructor() {this.metrics = {}; }startTimer(name) {const start = Date.now();return() => {const duration = Date.now() - start;this.recordMetric(name, duration); }; }recordMetric(name, value) {if (!this.metrics[name]) {this.metrics[name] = []; }this.metrics[name].push({ value,timestamp: Date.now() });// 保留最近 1000 条if (this.metrics[name].length > 1000) {this.metrics[name].shift(); } }getStats(name) {const values = this.metrics[name]?.map(m => m.value) || [];if (values.length === 0) {returnnull; }return {count: values.length,avg: values.reduce((a, b) => a + b, 0) / values.length,min: Math.min(...values),max: Math.max(...values),p95: this.percentile(values, 95) }; }percentile(values, p) {const sorted = values.sort((a, b) => a - b);const index = Math.ceil((p / 100) * sorted.length) - 1;return sorted[index]; }}// 使用示例const monitor = newPerformanceMonitor();asyncfunctionhandleRequest(request) {const stopTimer = monitor.startTimer('request_duration');try {returnawaitprocess(request); } finally {stopTimer(); }}// 查看性能统计const stats = monitor.getStats('request_duration');console.log(`平均响应时间:${stats.avg}ms, P95: ${stats.p95}ms`);✅ 学完这篇你能做什么
学完 Day 24,你将能够:
✅ 实现并发处理 ✅ 配置多层缓存 ✅ 优化资源使用 ✅ 实施性能监控 ✅ 处理性能相关问题
🔜 下篇预告
Day 25:自定义扩展:插件开发、中间件、钩子函数
🔌 插件开发 🔄 中间件 🎣 钩子函数
💬 互动环节
你遇到过什么性能瓶颈?如何解决的?留言分享!
公众号:OpenClaw 研习社
系列:OpenClaw 30 天入门到精通
作者:OpenClaw 研习社
夜雨聆风