Node.js后端开发从入门到进阶实战指南:如何解决异步编程与性能优化难题并构建高可用系统

Node.js作为基于Chrome V8引擎的JavaScript运行时环境,凭借其事件驱动、非阻塞I/O模型,已成为后端开发领域的主流技术栈。然而,从入门到进阶的过程中,开发者往往会面临异步编程的复杂性、性能瓶颈以及如何构建高可用系统的挑战。本文将深入探讨这些核心问题,并提供从基础概念到实战优化的完整指南。
一、Node.js异步编程模型深度解析
1.1 异步编程的核心概念与演进
Node.js的异步编程模型是其高性能的基石,但也是初学者面临的首要挑战。理解事件循环(Event Loop)是掌握异步编程的关键。
事件循环机制详解:
Node.js通过libuv库实现事件循环,它分为多个阶段,每个阶段处理特定类型的任务:
Timers阶段
:执行setTimeout和setInterval的回调
I/O callbacks阶段
:执行几乎所有的回调,除了close、timer和setImmediate
idle、prepare阶段
:仅内部使用
poll阶段
:检索新的I/O事件,执行I/O相关的回调
check阶段
:执行setImmediate的回调
close callbacks阶段
:执行socket的close事件回调
异步编程的演进历程:
回调函数(Callback)时代
:Node.js早期的主要方式,容易导致”回调地狱”
Promise时代
:ES6引入,提供了更优雅的链式调用
Async/Await时代
:ES2017引入,基于Promise的语法糖,让异步代码看起来像同步代码
1.2 回调地狱的产生与解决方案
回调地狱的典型示例:
// 典型的回调地狱代码,难以阅读和维护
fs.readFile(‘file1.txt’, ‘utf8’, (err, data1) => {
if (err) {
console.error(‘读取file1失败:’, err);
return;
}

fs.writeFile(‘file2.txt’, data1, (err) => {
if (err) {
console.error(‘写入file2失败:’, err);
return;
}

fs.readFile(‘file2.txt’, ‘utf8’, (err, data2) => {
if (err) {
console.error(‘读取file2失败:’, err);
return;
}

fs.writeFile(‘file3.txt’, data2, (err) => {
if (err) {
console.error(‘写入file3失败:’, err);
return;
}

console.log(‘文件处理完成’);
});
});
});
});
使用Promise重构:
const fs = require(‘fs’).promises;

// 使用Promise重构,代码结构更清晰
async function processFiles() {
try {
const data1 = await fs.readFile(‘file1.txt’, ‘utf8’);
await fs.writeFile(‘file2.txt’, data1);
const data2 = await fs.readFile(‘file2.txt’, ‘utf8’);
await fs.writeFile(‘file3.txt’, data2);
console.log(‘文件处理完成’);
} catch (error) {
console.error(‘处理失败:’, error);
}
}

processFiles();
1.3 Async/Await的正确使用模式
错误使用示例:
// 错误:没有正确处理错误,导致未捕获的Promise拒绝
async function fetchData() {
const result = await fetch(‘https://api.example.com/data’);
return result.json();
}

// 错误:没有使用try-catch,异常会导致进程崩溃
async function badPractice() {
const data = await fetchData(); // 如果fetch失败,未捕获的异常
console.log(data);
}
正确使用模式:
// 正确:完整的错误处理和资源管理
async function fetchDataWithRetry(url, maxRetries = 3) {
for (let i = 0; i < maxRetries; i++) { try { const response = await fetch(url); if (!response.ok) { throw new Error(`HTTP ${response.status}`); } return await response.json(); } catch (error) { if (i === maxRetries - 1) throw error; await new Promise(resolve => setTimeout(resolve, 1000 * (i + 1)));
}
}
}

// 正确:并发控制模式
async function processBatch(items, batchSize = 5) {
const results = [];
for (let i = 0; i < items.length; i += batchSize) { const batch = items.slice(i, i + batchSize); const batchResults = await Promise.all( batch.map(item => processItem(item))
);
results.push(…batchResults);
}
return results;
}
1.4 异步资源管理与内存泄漏防范
未正确处理异步资源导致内存泄漏:
// 错误示例:事件监听器未清理
const EventEmitter = require(‘events’);

class DataProcessor extends EventEmitter {
constructor() {
super();
this.data = [];
}

process(data) {
// 每次调用都添加监听器,但从不移除
this.on(‘data’, () => {
this.data.push(data);
});
this.emit(‘data’);
}
}

// 使用示例
const processor = new DataProcessor();
// 多次调用后,监听器数组无限增长
for (let i = 0; i < 1000; i++) { processor.process(i); } 正确的资源管理: // 正确:使用once或手动移除监听器 class DataProcessor extends EventEmitter { constructor() { super(); this.data = []; this.processing = false; } // 使用once确保监听器只执行一次 processOnce(data) { return new Promise((resolve) => {
this.once(‘processed’, () => {
this.data.push(data);
resolve();
});
this.emit(‘process’, data);
});
}

// 手动管理监听器
processWithCleanup(data) {
const handler = () => {
this.data.push(data);
this.removeListener(‘process’, handler); // 清理监听器
};
this.on(‘process’, handler);
this.emit(‘process’);
}

// 使用WeakMap存储临时数据,避免内存泄漏
processWithWeakMap(data) {
const tempData = new WeakMap();
tempData.set(this, data);
// 处理完成后,tempData会被自动垃圾回收
}
}
二、Node.js性能优化实战策略
2.1 CPU密集型任务优化
Node.js是单线程的,CPU密集型任务会阻塞事件循环。优化策略包括:
使用Worker Threads处理CPU密集型任务:
const { Worker, isMainThread, parentPort, workerData } = require(‘worker_threads’);
const path = require(‘path’);

// 工作线程文件:heavy-computation.js
if (!isMainThread) {
// 在工作线程中执行CPU密集型计算
const { data } = workerData;

// 模拟CPU密集型计算
function fibonacci(n) {
if (n <= 1) return n; return fibonacci(n - 1) + fibonacci(n - 2); } const result = fibonacci(data); parentPort.postMessage(result); } // 主线程:main.js function runHeavyComputation(n) { return new Promise((resolve, reject) => {
const worker = new Worker(path.resolve(__dirname, ‘heavy-computation.js’), {
workerData: { data: n }
});

worker.on(‘message’, resolve);
worker.on(‘error’, reject);
worker.on(‘exit’, (code) => {
if (code !== 0) {
reject(new Error(`Worker stopped with exit code ${code}`));
}
});
});
}

// 使用示例
async function main() {
console.time(‘Heavy Computation’);
const result = await runHeavyComputation(40);
console.timeEnd(‘Heavy Computation’);
console.log(‘Result:’, result);
}

main();
使用child_process处理更复杂的计算:
const { fork } = require(‘child_process’);
const path = require(‘path’);

// 计算进程:calculator.js
process.on(‘message’, (msg) => {
if (msg.type === ‘calculate’) {
const { a, b } = msg.data;
// 模拟复杂计算
const result = heavyCalculation(a, b);
process.send({ type: ‘result’, data: result });
}
});

function heavyCalculation(a, b) {
// 复杂的数学计算
let sum = 0;
for (let i = 0; i < 1e7; i++) { sum += Math.sin(i) * Math.cos(i); } return sum + a + b; } // 主进程 function calculateWithChild(a, b) { return new Promise((resolve) => {
const child = fork(path.resolve(__dirname, ‘calculator.js’));

child.on(‘message’, (msg) => {
if (msg.type === ‘result’) {
child.kill(); // 计算完成后终止子进程
resolve(msg.data);
}
});

child.send({ type: ‘calculate’, data: { a, b } });
});
}
2.2 I/O性能优化
数据库查询优化(使用连接池):
const mysql = require(‘mysql2/promise’);

// 创建连接池
const pool = mysql.createPool({
host: ‘localhost’,
user: ‘root’,
database: ‘test’,
waitForConnections: true,
connectionLimit: 10,
queueLimit: 0
});

// 优化前:每次查询都创建新连接(性能差)
async function badQuery() {
const connection = await mysql.createConnection({…});
const [rows] = await connection.execute(‘SELECT * FROM users WHERE id = ?’, [1]);
await connection.end();
return rows;
}

// 优化后:使用连接池
async function goodQuery() {
const [rows] = await pool.execute(‘SELECT * FROM users WHERE id = ?’, [1]);
return rows;
}

// 批量操作优化
async function batchInsert(users) {
// 使用事务保证数据一致性
const connection = await pool.getConnection();
try {
await connection.beginTransaction();

const placeholders = users.map(() => ‘(?, ?, ?)’).join(‘,’);
const values = users.flatMap(u => [u.id, u.name, u.email]);

await connection.execute(
`INSERT INTO users (id, name, email) VALUES ${placeholders}`,
values
);

await connection.commit();
} catch (error) {
await connection.rollback();
throw error;
} finally {
connection.release();
}
}
文件I/O优化(使用流):
const fs = require(‘fs’);
const { pipeline } = require(‘stream/promises’);

// 优化前:读取大文件到内存(内存爆炸风险)
async function processLargeFileBad(filePath) {
const data = await fs.promises.readFile(filePath); // 一次性读取
// 处理数据…
return data;
}

// 优化后:使用流处理大文件
async function processLargeFileGood(filePath) {
const readStream = fs.createReadStream(filePath, { encoding: ‘utf8’ });
const writeStream = fs.createWriteStream(filePath + ‘.processed’);

// 使用pipeline自动处理错误和资源清理
await pipeline(
readStream,
// 自定义转换流
new (require(‘stream’).Transform)({
transform(chunk, encoding, callback) {
// 逐块处理数据
const processed = chunk.toString().toUpperCase();
callback(null, processed);
}
}),
writeStream
);
}

// HTTP流式传输优化
const http = require(‘http’);

http.createServer(async (req, res) => {
if (req.url === ‘/large-file’) {
const fileStream = fs.createReadStream(‘./large-file.csv’);

// 设置响应头
res.writeHead(200, {
‘Content-Type’: ‘text/csv’,
‘Content-Disposition’: ‘attachment; filename=”data.csv”‘
});

// 流式传输,内存占用极低
fileStream.pipe(res);

// 错误处理
fileStream.on(‘error’, (err) => {
console.error(‘File stream error:’, err);
if (!res.headersSent) {
res.writeHead(500);
res.end(‘Error reading file’);
}
});
}
}).listen(3000);
2.2 内存优化与垃圾回收
内存泄漏检测与防范:
// 内存泄漏示例:全局数组无限增长
const leakyCache = [];

function addToCache(data) {
leakyCache.push(data); // 永远不会清理
}

// 正确:使用LRU缓存策略
const LRU = require(‘lru-cache’);

const cache = new LRU({
max: 500, // 最多存储500个条目
ttl: 1000 * 60 * 5 // 5分钟过期
});

function addToCacheSafe(key, value) {
cache.set(key, value);
}

// 使用WeakRef避免强引用
const weakCache = new Map();

function cacheWeakly(key, obj) {
weakCache.set(key, new WeakRef(obj));
}

// 检查缓存并清理
function getFromWeakCache(key) {
const ref = weakCache.get(key);
if (ref && ref.deref()) {
return ref.deref();
} else {
weakCache.delete(key);
return null;
}
}

// 监控内存使用
function monitorMemory() {
const used = process.memoryUsage();
console.log({
rss: `${Math.round(used.rss / 1024 / 1024)} MB`, // 常驻内存
heapTotal: `${Math.round(used.heapTotal / 1024 / 1024)} MB`, // V8堆内存总和
heapUsed: `${Math.round(used.heapUsed / 1024 / 1024)} MB`, // 已使用的堆内存
external: `${Math.round(used.external / 1024 / 1024)} MB` // C++对象占用的内存
});
}

// 定期监控
setInterval(monitorMemory, 5000);
2.3 事件循环监控
检测事件循环延迟:
// 监控事件循环延迟
function monitorEventLoop() {
let lastTime = Date.now();

setInterval(() => {
const now = Date.now();
const delay = now – lastTime – 1000; // 预期间隔1000ms

if (delay > 100) { // 延迟超过100ms警告
console.warn(`事件循环延迟: ${delay}ms`);
}

lastTime = now;
}, 1000);
}

// 使用blocked-at库检测阻塞
const blocked = require(‘blocked-at’);

blocked((duration, stack) => {
console.warn(`事件循环被阻塞 ${duration}ms`);
console.warn(‘Stack trace:’, stack);
});
三、构建高可用Node.js系统
3.1 错误处理与容错机制
全局错误处理:
// 未捕获的异常会导致进程退出
process.on(‘uncaughtException’, (err, origin) => {
console.error(‘未捕获的异常:’, err, ‘来源:’, origin);

// 记录错误日志
logErrorToFile(err);

// 重要:不要在此处尝试恢复,应该优雅退出
// 但可以执行清理操作
cleanupGracefully().then(() => {
process.exit(1);
});
});

// 未处理的Promise拒绝
process.on(‘unhandledRejection’, (reason, promise) => {
console.error(‘未处理的Promise拒绝:’, reason);
// 记录日志并继续运行(Node.js 15+默认会终止)
});

// Express中的错误处理中间件
const express = require(‘express’);
const app = express();

// 自定义错误类
class AppError extends Error {
constructor(message, statusCode) {
super(message);
this.statusCode = statusCode;
this.isOperational = true; // 标记是否为已知错误
}
}

// 全局错误处理中间件
app.use((err, req, res, next) => {
// 已知错误
if (err.isOperational) {
return res.status(err.statusCode).json({
error: err.message,
timestamp: new Date().toISOString()
});
}

// 未知错误(编程错误)
console.error(‘Unexpected error:’, err);

// 生产环境不暴露堆栈信息
res.status(500).json({
error: ‘Internal Server Error’,
…(process.env.NODE_ENV === ‘development’ && { stack: err.stack })
});
});

// 路由中的错误处理
app.get(‘/api/users/:id’, async (req, res, next) => {
try {
const user = await getUserById(req.params.id);
if (!user) {
throw new AppError(‘User not found’, 404);
}
res.json(user);
} catch (error) {
next(error); // 传递给错误处理中间件
}
});
断路器模式实现:
class CircuitBreaker {
constructor(threshold = 5, timeout = 60000) {
this.failureCount = 0;
this.successCount = 0;
this.threshold = threshold;
this.timeout = timeout;
this.state = ‘CLOSED’; // CLOSED, OPEN, HALF_OPEN
this.nextAttempt = Date.now();
}

async execute(fn) {
if (this.state === ‘OPEN’) {
if (Date.now() < this.nextAttempt) { throw new Error('Circuit breaker is OPEN'); } // 进入半开状态 this.state = 'HALF_OPEN'; } try { const result = await fn(); this.onSuccess(); return result; } catch (error) { this.onFailure(); throw error; } } onSuccess() { this.failureCount = 0; this.successCount++; if (this.state === 'HALF_OPEN') { this.state = 'CLOSED'; console.log('Circuit breaker closed'); } } onFailure() { this.failureCount++; this.successCount = 0; if (this.failureCount >= this.threshold) {
this.state = ‘OPEN’;
this.nextAttempt = Date.now() + this.timeout;
console.log(`Circuit breaker opened for ${this.timeout}ms`);
}
}

getState() {
return {
state: this.state,
failureCount: this.failureCount,
successCount: this.successCount,
nextAttempt: this.nextAttempt
};
}
}

// 使用示例
const breaker = new CircuitBreaker(3, 10000);

async function callExternalAPI() {
return breaker.execute(async () => {
// 模拟外部API调用
const response = await fetch(‘https://api.example.com/data’);
if (!response.ok) throw new Error(‘API Error’);
return response.json();
});
}
3.2 负载均衡与集群模式
使用Node.js集群模块:
const cluster = require(‘cluster’);
const os = require(‘os’);
const http = require(‘http’);

if (cluster.isMaster) {
const numCPUs = os.cpus().length;

console.log(`Master ${process.pid} is running`);
console.log(`Forking ${numCPUs} workers…`);

// 根据CPU核心数创建工作进程
for (let i = 0; i < numCPUs; i++) { cluster.fork(); } // 监听工作进程事件 cluster.on('exit', (worker, code, signal) => {
console.log(`Worker ${worker.process.pid} died`);
// 自动重启
cluster.fork();
});

// 进程管理
process.on(‘SIGTERM’, () => {
console.log(‘Master received SIGTERM, shutting down gracefully’);
for (const id in cluster.workers) {
cluster.workers[id].send(‘shutdown’);
}
process.exit(0);
});
} else {
// 工作进程
const server = http.createServer((req, res) => {
if (req.url === ‘/health’) {
res.writeHead(200);
res.end(‘OK’);
return;
}

// 模拟工作负载
const start = Date.now();
while (Date.now() – start < 100) {} // 100ms CPU工作 res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end(`Hello from worker ${process.pid}\n`); }); server.listen(3000, () => {
console.log(`Worker ${process.pid} started on port 3000`);
});

// 优雅关闭
process.on(‘message’, (msg) => {
if (msg === ‘shutdown’) {
console.log(`Worker ${process.pid} shutting down gracefully`);
server.close(() => {
process.exit(0);
});
}
});
}
使用PM2进行进程管理:
# 安装PM2
npm install -g pm2

# 启动应用(集群模式)
pm2 start app.js -i max –name “my-app”

# 配置文件 ecosystem.config.js
module.exports = {
apps: [{
name: ‘my-app’,
script: ‘./app.js’,
instances: ‘max’, // 使用所有CPU核心
exec_mode: ‘cluster’, // 集群模式
env: {
NODE_ENV: ‘production’
},
error_file: ‘./logs/err.log’,
out_file: ‘./logs/out.log’,
log_file: ‘./logs/combined.log’,
time: true,
max_memory_restart: ‘1G’, // 内存超过1GB自动重启
watch: false,
env_production: {
NODE_ENV: ‘production’,
PORT: 3000
}
}]
};

# 使用配置文件启动
pm2 start ecosystem.config.js –env production

# 监控
pm2 monit

# 日志
pm2 logs

# 重启
pm2 restart my-app

# 零停机重启
pm2 reload my-app
3.3 性能监控与指标收集
使用Prometheus和Grafana监控:
const client = require(‘prom-client’);

// 创建指标
const httpRequestsTotal = new client.Counter({
name: ‘http_requests_total’,
help: ‘Total number of HTTP requests’,
labelNames: [‘method’, ‘route’, ‘status’]
});

const httpRequestDuration = new client.Histogram({
name: ‘http_request_duration_seconds’,
help: ‘Duration of HTTP requests in seconds’,
labelNames: [‘method’, ‘route’],
buckets: [0.1, 0.5, 1, 2, 5]
});

const memoryUsageGauge = new client.Gauge({
name: ‘nodejs_memory_usage_bytes’,
help: ‘Node.js memory usage’,
labelNames: [‘type’]
});

// Express中间件收集指标
function metricsMiddleware(req, res, next) {
const start = Date.now();

res.on(‘finish’, () => {
const duration = (Date.now() – start) / 1000;
const route = req.route ? req.route.path : req.path;

httpRequestsTotal.inc({
method: req.method,
route: route,
status: res.statusCode
});

httpRequestDuration.observe({
method: req.method,
route: route
}, duration);
});

next();
}

// 定期收集内存指标
setInterval(() => {
const used = process.memoryUsage();
memoryUsageGauge.set({ type: ‘heapUsed’ }, used.heapUsed);
memoryUsageGauge.set({ type: ‘heapTotal’ }, used.heapTotal);
memoryUsageGauge.set({ type: ‘rss’ }, used.rss);
}, 5000);

// 暴露指标端点
app.get(‘/metrics’, async (req, res) => {
res.set(‘Content-Type’, client.register.contentType);
res.end(await client.register.metrics());
});

app.use(metricsMiddleware);
3.4 缓存策略实现
Redis缓存实现:
const redis = require(‘redis’);
const { promisify } = require(‘util’);

// 创建Redis客户端
const client = redis.createClient({
host: ‘localhost’,
port: 6379,
password: process.env.REDIS_PASSWORD
});

client.on(‘error’, (err) => console.error(‘Redis Client Error’, err));

// 将回调函数转换为Promise
const getAsync = promisify(client.get).bind(client);
const setAsync = promisify(client.set).bind(client);
const delAsync = promisify(client.del).bind(client);

// 缓存装饰器
function cacheable(ttl = 300) {
return function(target, propertyKey, descriptor) {
const originalMethod = descriptor.value;

descriptor.value = async function(…args) {
const key = `${propertyKey}:${JSON.stringify(args)}`;

// 尝试从缓存获取
const cached = await getAsync(key);
if (cached) {
console.log(‘Cache hit:’, key);
return JSON.parse(cached);
}

// 执行原始方法
const result = await originalMethod.apply(this, args);

// 存入缓存
await setAsync(key, JSON.stringify(result), ‘EX’, ttl);
console.log(‘Cache miss, stored:’, key);

return result;
};

return descriptor;
};
}

// 使用示例
class UserService {
@cacheable(60) // 缓存60秒
async getUserById(id) {
// 模拟数据库查询
await new Promise(resolve => setTimeout(resolve, 100));
return { id, name: `User ${id}`, email: `user${id}@example.com` };
}
}

// 缓存穿透防护
async function getWithCachePenetrationProtection(key, fallbackFn, ttl = 300) {
const cacheKey = `cache:${key}`;

// 尝试缓存
const cached = await getAsync(cacheKey);
if (cached) {
if (cached === ‘null’) return null; // 缓存空值
return JSON.parse(cached);
}

// 防止并发穿透
const lockKey = `lock:${key}`;
const lock = await setAsync(lockKey, ‘1’, ‘NX’, ‘EX’, 10);

if (!lock) {
// 其他线程正在加载,等待后重试
await new Promise(resolve => setTimeout(resolve, 100));
return getWithCachePenetrationProtection(key, fallbackFn, ttl);
}

try {
const result = await fallbackFn();
const value = result === null ? ‘null’ : JSON.stringify(result);
await setAsync(cacheKey, value, ‘EX’, ttl);
return result;
} finally {
await delAsync(lockKey);
}
}
3.5 数据库优化与连接管理
MongoDB连接池优化:
const mongoose = require(‘mongoose’);

// 连接配置
mongoose.connect(‘mongodb://localhost:27017/myapp’, {
maxPoolSize: 10, // 最大连接数
minPoolSize: 2, // 最小连接数
maxIdleTimeMS: 30000, // 连接最大空闲时间
socketTimeoutMS: 45000, // socket超时
serverSelectionTimeoutMS: 5000, // 服务器选择超时
heartbeatFrequencyMS: 10000, // 心跳频率
retryWrites: true, // 重试写入操作
retryReads: true // 重试读取操作
});

// 连接事件监听
mongoose.connection.on(‘connected’, () => {
console.log(‘Mongoose connected to MongoDB’);
});

mongoose.connection.on(‘error’, (err) => {
console.error(‘Mongoose connection error:’, err);
});

mongoose.connection.on(‘disconnected’, () => {
console.log(‘Mongoose disconnected’);
});

// 查询优化
async function optimizedQuery() {
// 使用索引
const user = await User.findOne({ email: ‘test@example.com’ }).lean(); // lean()返回纯JS对象,更快

// 分页查询
const page = 1;
const limit = 10;
const users = await User.find()
.skip((page – 1) * limit)
.limit(limit)
.sort({ createdAt: -1 })
.select(‘name email’) // 只选择需要的字段
.lean();

return users;
}

// 批量操作
async function batchUpdate() {
const bulkOps = users.map(user => ({
updateOne: {
filter: { _id: user._id },
update: { $set: { lastLogin: new Date() } }
}
}));

await User.bulkWrite(bulkOps);
}
四、实战:构建高可用电商API系统
4.1 系统架构设计
项目结构:
project/
├── src/
│ ├── config/ # 配置管理
│ ├── controllers/ # 控制器
│ ├── services/ # 业务逻辑
│ ├── models/ # 数据模型
│ ├── middleware/ # 中间件
│ ├── utils/ # 工具函数
│ ├── routes/ # 路由
│ └── app.js # 应用入口
├── logs/ # 日志文件
├── ecosystem.config.js # PM2配置
└── package.json
核心应用代码:
// src/app.js
const express = require(‘express’);
const cors = require(‘cors’);
const helmet = require(‘helmet’);
const compression = require(‘compression’);
const rateLimit = require(‘express-rate-limit’);
const { connectDB } = require(‘./config/database’);
const { errorHandler } = require(‘./middleware/errorHandler’);
const { requestLogger } = require(‘./middleware/requestLogger’);
const metricsMiddleware = require(‘./middleware/metrics’);

// 创建Express应用
const app = express();

// 安全中间件
app.use(helmet());
app.use(cors({
origin: process.env.ALLOWED_ORIGINS?.split(‘,’) || [‘http://localhost:3000′],
credentials: true
}));

// 性能中间件
app.use(compression());
app.use(express.json({ limit: ’10mb’ }));
app.use(express.urlencoded({ extended: true, limit: ’10mb’ }));

// 限流中间件
const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15分钟
max: 100, // 每个IP最多100个请求
standardHeaders: true,
legacyHeaders: false,
message: ‘Too many requests from this IP’
});
app.use(‘/api/’, limiter);

// 自定义中间件
app.use(requestLogger);
app.use(metricsMiddleware);

// 路由
app.use(‘/api/auth’, require(‘./routes/auth’));
app.use(‘/api/products’, require(‘./routes/products’));
app.use(‘/api/orders’, require(‘./routes/orders’));

// 健康检查
app.get(‘/health’, (req, res) => {
res.status(200).json({
status: ‘OK’,
timestamp: new Date().toISOString(),
uptime: process.uptime(),
memory: process.memoryUsage()
});
});

// 错误处理(必须放在最后)
app.use(errorHandler);

// 启动函数
async function startServer() {
try {
await connectDB();

const PORT = process.env.PORT || 3000;
const server = app.listen(PORT, () => {
console.log(`Server running on port ${PORT} in ${process.env.NODE_ENV} mode`);
});

// 优雅关闭
const gracefulShutdown = async (signal) => {
console.log(`Received ${signal}, shutting down gracefully`);

server.close(() => {
console.log(‘HTTP server closed’);
process.exit(0);
});

// 强制关闭
setTimeout(() => {
console.error(‘Force shutdown’);
process.exit(1);
}, 10000);
};

process.on(‘SIGTERM’, () => gracefulShutdown(‘SIGTERM’));
process.on(‘SIGINT’, () => gracefulShutdown(‘SIGINT’));

} catch (error) {
console.error(‘Failed to start server:’, error);
process.exit(1);
}
}

module.exports = { app, startServer };
4.2 业务逻辑实现
产品服务(带缓存和断路器):
// src/services/productService.js
const Product = require(‘../models/Product’);
const redis = require(‘../config/redis’);
const CircuitBreaker = require(‘../utils/circuitBreaker’);

class ProductService {
constructor() {
this.breaker = new CircuitBreaker(3, 30000); // 3次失败,30秒超时
}

// 获取产品详情(带缓存)
async getProductById(id) {
const cacheKey = `product:${id}`;

// 尝试缓存
const cached = await redis.get(cacheKey);
if (cached) {
return JSON.parse(cached);
}

// 使用断路器保护数据库查询
const product = await this.breaker.execute(async () => {
return await Product.findById(id).lean();
});

if (product) {
// 缓存结果
await redis.setex(cacheKey, 300, JSON.stringify(product)); // 5分钟
}

return product;
}

// 批量获取产品
async getProducts(ids) {
const products = await Promise.all(
ids.map(id => this.getProductById(id))
);
return products.filter(p => p !== null);
}

// 创建产品(缓存失效)
async createProduct(data) {
const product = new Product(data);
await product.save();

// 清理相关缓存
await redis.del(`product:${product._id}`);

return product;
}

// 更新产品(缓存失效)
async updateProduct(id, data) {
const product = await Product.findByIdAndUpdate(id, data, { new: true });
if (product) {
// 更新缓存
await redis.setex(`product:${id}`, 300, JSON.stringify(product));
}
return product;
}

// 删除产品(缓存失效)
async deleteProduct(id) {
await Product.findByIdAndDelete(id);
await redis.del(`product:${id}`);
return true;
}
}

module.exports = new ProductService();
订单服务(事务处理):
// src/services/orderService.js
const Order = require(‘../models/Order’);
const Product = require(‘../models/Product’);
const mongoose = require(‘mongoose’);

class OrderService {
// 创建订单(事务处理)
async createOrder(userId, items) {
const session = await mongoose.startSession();

try {
session.startTransaction();

// 1. 验证库存
for (const item of items) {
const product = await Product.findById(item.productId).session(session);
if (!product || product.stock < item.quantity) { throw new Error(`Insufficient stock for product ${item.productId}`); } // 扣减库存 product.stock -= item.quantity; await product.save({ session }); } // 2. 创建订单 const order = new Order({ userId, items, status: 'pending', totalAmount: items.reduce((sum, item) => sum + item.price * item.quantity, 0)
});

await order.save({ session });

// 3. 提交事务
await session.commitTransaction();

// 4. 异步处理(发送邮件、通知等)
this.processOrderAsync(order).catch(err => {
console.error(‘Async order processing failed:’, err);
// 记录失败,后续补偿
});

return order;

} catch (error) {
await session.abortTransaction();
throw error;
} finally {
session.endSession();
}
}

// 异步订单处理
async processOrderAsync(order) {
// 发送确认邮件(使用队列)
await this.addToEmailQueue(order.userId, ‘order_confirmation’, {
orderId: order._id,
items: order.items
});

// 更新分析数据
await this.updateAnalytics(order);
}

// 获取用户订单(分页)
async getUserOrders(userId, page = 1, limit = 10) {
const skip = (page – 1) * limit;

const [orders, total] = await Promise.all([
Order.find({ userId })
.sort({ createdAt: -1 })
.skip(skip)
.limit(limit)
.lean(),
Order.countDocuments({ userId })
]);

return {
orders,
pagination: {
page,
limit,
total,
pages: Math.ceil(total / limit)
}
};
}
}

module.exports = new OrderService();
4.3 中间件实现
请求日志中间件:
// src/middleware/requestLogger.js
const winston = require(‘winston’);
const { format } = winston;

// 配置Winston日志
const logger = winston.createLogger({
level: ‘info’,
format: format.combine(
format.timestamp(),
format.errors({ stack: true }),
format.json()
),
transports: [
new winston.transports.File({ filename: ‘logs/error.log’, level: ‘error’ }),
new winston.transports.File({ filename: ‘logs/combined.log’ })
]
});

if (process.env.NODE_ENV !== ‘production’) {
logger.add(new winston.transports.Console({
format: format.combine(
format.colorize(),
format.simple()
)
}));
}

// 请求日志中间件
function requestLogger(req, res, next) {
const start = Date.now();

res.on(‘finish’, () => {
const duration = Date.now() – start;
const logData = {
method: req.method,
url: req.originalUrl,
statusCode: res.statusCode,
duration: `${duration}ms`,
ip: req.ip,
userAgent: req.get(‘User-Agent’),
timestamp: new Date().toISOString()
};

logger.info(‘API Request’, logData);

// 慢请求警告
if (duration > 1000) {
logger.warn(‘Slow request detected’, logData);
}
});

next();
}

module.exports = { requestLogger, logger };
错误处理中间件:
// src/middleware/errorHandler.js
const { logger } = require(‘./requestLogger’);

// 错误分类
function classifyError(error) {
if (error.name === ‘ValidationError’) {
return { status: 400, message: ‘Validation failed’, details: error.errors };
}
if (error.name === ‘CastError’) {
return { status: 400, message: ‘Invalid ID format’ };
}
if (error.code === 11000) {
return { status: 409, message: ‘Duplicate key error’, field: Object.keys(error.keyPattern)[0] };
}
if (error.name === ‘JsonWebTokenError’) {
return { status: 401, message: ‘Invalid token’ };
}
if (error.name === ‘TokenExpiredError’) {
return { status: 401, message: ‘Token expired’ };
}

// 默认
return { status: 500, message: ‘Internal Server Error’ };
}

function errorHandler(err, req, res, next) {
// 记录错误
logger.error(‘Request error’, {
error: err.message,
stack: err.stack,
url: req.originalUrl,
method: req.method,
body: req.body,
params: req.params,
query: req.query
});

// 分类错误
const classified = classifyError(err);

// 开发环境返回堆栈
const response = {
error: classified.message,
…(classified.details && { details: classified.details }),
…(classified.field && { field: classified.field }),
…(process.env.NODE_ENV === ‘development’ && { stack: err.stack })
};

res.status(classified.status).json(response);
}

module.exports = { errorHandler };
认证中间件:
// src/middleware/auth.js
const jwt = require(‘jsonwebtoken’);
const User = require(‘../models/User’);

// JWT验证
function authenticateToken(req, res, next) {
const authHeader = req.headers[‘authorization’];
const token = authHeader && authHeader.split(‘ ‘)[1]; // Bearer TOKEN

if (!token) {
return res.status(401).json({ error: ‘Access token required’ });
}

jwt.verify(token, process.env.JWT_SECRET, (err, user) => {
if (err) {
return res.status(403).json({ error: ‘Invalid or expired token’ });
}
req.user = user;
next();
});
}

// 角色权限验证
function authorize(roles = []) {
return (req, res, next) => {
if (!req.user) {
return res.status(401).json({ error: ‘Authentication required’ });
}

if (roles.length && !roles.includes(req.user.role)) {
return res.status(403).json({ error: ‘Insufficient permissions’ });
}

next();
};
}

// 速率限制(基于用户)
const rateLimit = require(‘express-rate-limit’);
const RedisStore = require(‘rate-limit-redis’);

const userRateLimiter = rateLimit({
store: new RedisStore({
client: require(‘../config/redis’).client
}),
windowMs: 15 * 60 * 1000,
max: 100,
keyGenerator: (req) => `user:${req.user?.id || req.ip}`,
handler: (req, res) => {
res.status(429).json({
error: ‘Too many requests’,
retryAfter: Math.ceil(req.rateLimit.resetTime / 1000)
});
}
});

module.exports = { authenticateToken, authorize, userRateLimiter };
4.4 路由定义
认证路由:
// src/routes/auth.js
const express = require(‘express’);
const bcrypt = require(‘bcrypt’);
const jwt = require(‘jsonwebtoken’);
const User = require(‘../models/User’);
const { authenticateToken } = require(‘../middleware/auth’);
const { logger } = require(‘../middleware/requestLogger’);

const router = express.Router();

// 注册
router.post(‘/register’, async (req, res, next) => {
try {
const { email, password, name } = req.body;

// 验证输入
if (!email || !password || !name) {
return res.status(400).json({ error: ‘Missing required fields’ });
}

// 检查用户是否已存在
const existingUser = await User.findOne({ email });
if (existingUser) {
return res.status(409).json({ error: ‘User already exists’ });
}

// 哈希密码
const hashedPassword = await bcrypt.hash(password, 12);

// 创建用户
const user = new User({
email,
password: hashedPassword,
name,
role: ‘user’
});

await user.save();

// 生成JWT
const token = jwt.sign(
{ userId: user._id, role: user.role },
process.env.JWT_SECRET,
{ expiresIn: ’24h’ }
);

logger.info(‘User registered’, { userId: user._id, email });

res.status(201).json({
message: ‘User registered successfully’,
token,
user: {
id: user._id,
email: user.email,
name: user.name,
role: user.role
}
});

} catch (error) {
next(error);
}
});

// 登录
router.post(‘/login’, async (req, res, next) => {
try {
const { email, password } = req.body;

const user = await User.findOne({ email });
if (!user) {
return res.status(401).json({ error: ‘Invalid credentials’ });
}

const isValidPassword = await bcrypt.compare(password, user.password);
if (!isValidPassword) {
return res.status(401).json({ error: ‘Invalid credentials’ });
}

const token = jwt.sign(
{ userId: user._id, role: user.role },
process.env.JWT_SECRET,
{ expiresIn: ’24h’ }
);

logger.info(‘User logged in’, { userId: user._id });

res.json({
message: ‘Login successful’,
token,
user: {
id: user._id,
email: user.email,
name: user.name,
role: user.role
}
});

} catch (error) {
next(error);
}
});

// 获取当前用户
router.get(‘/me’, authenticateToken, async (req, res, next) => {
try {
const user = await User.findById(req.user.userId).select(‘-password’);
res.json(user);
} catch (error) {
next(error);
}
});

module.exports = router;
产品路由:
// src/routes/products.js
const express = require(‘express’);
const { authenticateToken, authorize } = require(‘../middleware/auth’);
const productService = require(‘../services/productService’);
const { userRateLimiter } = require(‘../middleware/auth’);

const router = express.Router();

// 获取产品列表(带缓存)
router.get(‘/’, userRateLimiter, async (req, res, next) => {
try {
const { page = 1, limit = 20, category, search } = req.query;

// 构建查询条件
const filter = {};
if (category) filter.category = category;
if (search) {
filter.$or = [
{ name: { $regex: search, $options: ‘i’ } },
{ description: { $regex: search, $options: ‘i’ } }
];
}

const skip = (page – 1) * limit;

const [products, total] = await Promise.all([
productService.getProducts(filter, skip, parseInt(limit)),
productService.countProducts(filter)
]);

res.json({
products,
pagination: {
page: parseInt(page),
limit: parseInt(limit),
total,
pages: Math.ceil(total / limit)
}
});

} catch (error) {
next(error);
}
});

// 获取单个产品
router.get(‘/:id’, userRateLimiter, async (req, res, next) => {
try {
const product = await productService.getProductById(req.params.id);
if (!product) {
return res.status(404).json({ error: ‘Product not found’ });
}
res.json(product);
} catch (error) {
next(error);
}
});

// 创建产品(需要管理员权限)
router.post(‘/’, authenticateToken, authorize([‘admin’]), async (req, res, next) => {
try {
const product = await productService.createProduct(req.body);
res.status(201).json(product);
} catch (error) {
next(error);
}
});

// 更新产品
router.put(‘/:id’, authenticateToken, authorize([‘admin’]), async (req, res, next) => {
try {
const product = await productService.updateProduct(req.params.id, req.body);
if (!product) {
return res.status(404).json({ error: ‘Product not found’ });
}
res.json(product);
} catch (error) {
next(error);
}
});

// 删除产品
router.delete(‘/:id’, authenticateToken, authorize([‘admin’]), async (req, res, next) => {
try {
await productService.deleteProduct(req.params.id);
res.json({ message: ‘Product deleted successfully’ });
} catch (error) {
next(error);
}
});

module.exports = router;
4.5 数据模型
用户模型:
// src/models/User.js
const mongoose = require(‘mongoose’);

const userSchema = new mongoose.Schema({
email: {
type: String,
required: true,
unique: true,
lowercase: true,
trim: true,
match: [/^\S+@\S+\.\S+$/, ‘Please enter a valid email’]
},
password: {
type: String,
required: true,
minlength: 8
},
name: {
type: String,
required: true,
trim: true
},
role: {
type: String,
enum: [‘user’, ‘admin’],
default: ‘user’
},
lastLogin: {
type: Date
}
}, {
timestamps: true
});

// 索引优化
userSchema.index({ email: 1 });
userSchema.index({ role: 1 });

module.exports = mongoose.model(‘User’, userSchema);
产品模型:
// src/models/Product.js
const mongoose = require(‘mongoose’);

const productSchema = new mongoose.Schema({
name: {
type: String,
required: true,
trim: true,
maxlength: 100
},
description: {
type: String,
required: true,
maxlength: 1000
},
price: {
type: Number,
required: true,
min: 0
},
category: {
type: String,
required: true,
index: true
},
stock: {
type: Number,
required: true,
min: 0,
default: 0
},
images: [String],
tags: [String],
isActive: {
type: Boolean,
default: true
}
}, {
timestamps: true,
toJSON: { virtuals: true },
toObject: { virtuals: true }
});

// 虚拟字段
productSchema.virtual(‘formattedPrice’).get(function() {
return `$${this.price.toFixed(2)}`;
});

// 复合索引
productSchema.index({ category: 1, price: 1 });
productSchema.index({ tags: 1 });
productSchema.index({ name: ‘text’, description: ‘text’ });

// 预保存钩子
productSchema.pre(‘save’, function(next) {
if (this.isModified(‘price’)) {
// 记录价格变更历史(可以存储到另一个集合)
this.wasNew = this.isNew;
}
next();
});

module.exports = mongoose.model(‘Product’, productSchema);
订单模型:
// src/models/Order.js
const mongoose = require(‘mongoose’);

const orderItemSchema = new mongoose.Schema({
productId: {
type: mongoose.Schema.Types.ObjectId,
ref: ‘Product’,
required: true
},
quantity: {
type: Number,
required: true,
min: 1
},
price: {
type: Number,
required: true
}
});

const orderSchema = new mongoose.Schema({
userId: {
type: mongoose.Schema.Types.ObjectId,
ref: ‘User’,
required: true,
index: true
},
items: [orderItemSchema],
status: {
type: String,
enum: [‘pending’, ‘confirmed’, ‘shipped’, ‘delivered’, ‘cancelled’],
default: ‘pending’,
index: true
},
totalAmount: {
type: Number,
required: true,
min: 0
},
shippingAddress: {
type: String,
required: true
}
}, {
timestamps: true
});

// 索引
orderSchema.index({ userId: 1, createdAt: -1 });
orderSchema.index({ status: 1 });

// 聚合查询方法
orderSchema.statics.getUserOrderStats = async function(userId) {
return this.aggregate([
{ $match: { userId: mongoose.Types.ObjectId(userId) } },
{
$group: {
_id: ‘$status’,
count: { $sum: 1 },
total: { $sum: ‘$totalAmount’ }
}
}
]);
};

module.exports = mongoose.model(‘Order’, orderSchema);
4.6 配置管理
数据库配置:
// src/config/database.js
const mongoose = require(‘mongoose’);

const config = {
development: {
url: process.env.MONGODB_URL || ‘mongodb://localhost:27017/myapp_dev’,
options: {
maxPoolSize: 5,
minPoolSize: 1
}
},
production: {
url: process.env.MONGODB_URL,
options: {
maxPoolSize: 20,
minPoolSize: 5,
maxIdleTimeMS: 30000,
socketTimeoutMS: 45000,
serverSelectionTimeoutMS: 5000,
retryWrites: true,
retryReads: true
}
}
};

async function connectDB() {
const env = process.env.NODE_ENV || ‘development’;
const { url, options } = config[env];

try {
await mongoose.connect(url, options);
console.log(`Connected to MongoDB in ${env} mode`);

mongoose.connection.on(‘error’, (err) => {
console.error(‘MongoDB connection error:’, err);
});

mongoose.connection.on(‘disconnected’, () => {
console.log(‘MongoDB disconnected’);
});

} catch (error) {
console.error(‘Failed to connect to MongoDB:’, error);
process.exit(1);
}
}

module.exports = { connectDB };
Redis配置:
// src/config/redis.js
const redis = require(‘redis’);

const config = {
development: {
host: ‘localhost’,
port: 6379,
password: null
},
production: {
host: process.env.REDIS_HOST,
port: process.env.REDIS_PORT,
password: process.env.REDIS_PASSWORD,
retry_strategy: (options) => {
if (options.error && options.error.code === ‘ECONNREFUSED’) {
return new Error(‘Redis server refused connection’);
}
if (options.total_retry_time > 1000 * 60 * 60) {
return new Error(‘Retry time exhausted’);
}
if (options.attempt > 10) {
return undefined;
}
return Math.min(options.attempt * 100, 3000);
}
}
};

const client = redis.createClient(config[process.env.NODE_ENV || ‘development’]);

client.on(‘error’, (err) => {
console.error(‘Redis Client Error’, err);
});

client.on(‘connect’, () => {
console.log(‘Redis connected’);
});

client.on(‘ready’, () => {
console.log(‘Redis ready’);
});

client.on(‘reconnecting’, () => {
console.log(‘Redis reconnecting’);
});

module.exports = client;
环境配置:
// src/config/index.js
require(‘dotenv’).config();

const config = {
port: process.env.PORT || 3000,
nodeEnv: process.env.NODE_ENV || ‘development’,

// JWT
jwtSecret: process.env.JWT_SECRET || ‘your-secret-key’,
jwtExpiresIn: process.env.JWT_EXPIRES_IN || ’24h’,

// 数据库
mongodbUrl: process.env.MONGODB_URL,

// Redis
redisHost: process.env.REDIS_HOST,
redisPort: process.env.REDIS_PORT,

// API
allowedOrigins: process.env.ALLOWED_ORIGINS?.split(‘,’) || [‘http://localhost:3000’],

// 限流
rateLimitWindowMs: 15 * 60 * 1000,
rateLimitMax: 100,

// 日志
logLevel: process.env.LOG_LEVEL || ‘info’,

// 性能
enableMetrics: process.env.ENABLE_METRICS === ‘true’,
slowQueryThreshold: 1000
};

module.exports = config;
4.7 启动脚本与PM2配置
启动脚本:
// src/server.js
const { startServer } = require(‘./app’);

// 启动服务器
startServer().catch(err => {
console.error(‘Failed to start server:’, err);
process.exit(1);
});
PM2生态系统配置:
// ecosystem.config.js
module.exports = {
apps: [{
name: ‘ecommerce-api’,
script: ‘./src/server.js’,
instances: ‘max’,
exec_mode: ‘cluster’,
env: {
NODE_ENV: ‘development’,
PORT: 3000
},
env_production: {
NODE_ENV: ‘production’,
PORT: 3000,
MONGODB_URL: ‘mongodb://localhost:27017/myapp’,
REDIS_HOST: ‘localhost’,
REDIS_PORT: 6379,
JWT_SECRET: ‘your-super-secret-jwt-key’,
ALLOWED_ORIGINS: ‘https://yourdomain.com,https://app.yourdomain.com’,
ENABLE_METRICS: ‘true’
},
error_file: ‘./logs/err.log’,
out_file: ‘./logs/out.log’,
log_file: ‘./logs/combined.log’,
time: true,
max_memory_restart: ‘1G’,
watch: false,
autorestart: true,
max_restarts: 10,
min_uptime: ’10s’,
listen_timeout: 5000,
kill_timeout: 5000,
env_test: {
NODE_ENV: ‘test’,
PORT: 3001
}
}]
};
package.json脚本:
{
“scripts”: {
“start”: “node src/server.js”,
“dev”: “nodemon src/server.js”,
“start:prod”: “pm2 start ecosystem.config.js –env production”,
“stop:prod”: “pm2 stop ecosystem.config.js”,
“restart:prod”: “pm2 restart ecosystem.config.js”,
“logs”: “pm2 logs”,
“monitor”: “pm2 monit”,
“test”: “jest”,
“test:watch”: “jest –watch”,
“lint”: “eslint src/**/*.js”,
“format”: “prettier –write \”src/**/*.js\””
}
}
五、进阶主题:微服务与容器化
5.1 微服务架构设计
API网关实现:
// gateway.js
const express = require(‘express’);
const httpProxy = require(‘http-proxy’);
const rateLimit = require(‘express-rate-limit’);
const { authenticateToken } = require(‘./middleware/auth’);

const app = express();
const proxy = httpProxy.createProxyServer();

// 服务路由配置
const serviceRoutes = {
‘/api/users’: ‘http://user-service:3001’,
‘/api/products’: ‘http://product-service:3002’,
‘/api/orders’: ‘http://order-service:3003’,
‘/api/payments’: ‘http://payment-service:3004’
};

// 全局限流
const globalLimiter = rateLimit({
windowMs: 60 * 1000,
max: 1000,
message: ‘Too many requests from this IP’
});

app.use(globalLimiter);

// 认证中间件
app.use(‘/api/*’, authenticateToken);

// 动态代理
app.use(‘/api’, (req, res) => {
const path = req.path.split(‘/’)[1];
const target = serviceRoutes[`/api/${path}`];

if (!target) {
return res.status(404).json({ error: ‘Service not found’ });
}

proxy.web(req, res, {
target,
changeOrigin: true,
timeout: 5000,
proxyTimeout: 5000,
onProxyReq: (proxyReq, req, res) => {
// 传递用户信息
if (req.user) {
proxyReq.setHeader(‘X-User-Id’, req.user.userId);
proxyReq.setHeader(‘X-User-Role’, req.user.role);
}
},
onProxyRes: (proxyRes, req, res) => {
// 记录响应时间
const start = req.startTime || Date.now();
console.log(`[${req.method}] ${req.path} -> ${target} – ${Date.now() – start}ms`);
},
onError: (err, req, res) => {
console.error(‘Proxy error:’, err);
res.status(502).json({ error: ‘Service unavailable’ });
}
});
});

// 健康检查端点
app.get(‘/health’, async (req, res) => {
const health = {
status: ‘OK’,
timestamp: new Date().toISOString(),
services: {}
};

// 检查各服务健康状态
for (const [path, target] of Object.entries(serviceRoutes)) {
try {
const response = await fetch(`${target}/health`, { timeout: 2000 });
health.services[path] = response.ok ? ‘healthy’ : ‘unhealthy’;
} catch (e) {
health.services[path] = ‘unreachable’;
}
}

const isHealthy = Object.values(health.services).every(s => s === ‘healthy’);
res.status(isHealthy ? 200 : 503).json(health);
});

app.listen(8000, () => {
console.log(‘API Gateway running on port 8000’);
});
5.2 Docker容器化
Dockerfile:
# 多阶段构建
FROM node:18-alpine AS builder

WORKDIR /app

# 复制package.json和lock文件
COPY package*.json ./

# 安装依赖(包括devDependencies)
RUN npm ci

# 复制源代码
COPY src/ ./src/

# 构建(如果有构建步骤)
# RUN npm run build

# 生产阶段
FROM node:18-alpine AS production

WORKDIR /app

# 创建非root用户
RUN addgroup -g 1001 -S nodejs
RUN adduser -S nodejs -u 1001

# 复制package.json
COPY package*.json ./

# 只安装生产依赖
RUN npm ci –only=production && npm cache clean –force

# 复制构建好的代码
COPY –from=builder /app/src ./src
COPY –from=builder /app/node_modules ./node_modules

# 创建日志目录
RUN mkdir -p logs && chown -R nodejs:nodejs /app

# 切换到非root用户
USER nodejs

# 暴露端口
EXPOSE 3000

# 健康检查
HEALTHCHECK –interval=30s –timeout=3s –start-period=5s –retries=3 \
CMD node -e “require(‘http’).get(‘http://localhost:3000/health’, (r) => {process.exit(r.statusCode === 200 ? 0 : 1)})”

# 启动命令
CMD [“node”, “src/server.js”]
Docker Compose配置:
# docker-compose.yml
version: ‘3.8’

services:
app:
build:
context: .
target: production
container_name: ecommerce-api
ports:
– “3000:3000”
environment:
– NODE_ENV=production
– PORT=3000
– MONGODB_URL=mongodb://mongodb:27017/myapp
– REDIS_HOST=redis
– REDIS_PORT=6379
– JWT_SECRET=${JWT_SECRET}
depends_on:
– mongodb
– redis
restart: unless-stopped
deploy:
resources:
limits:
cpus: ‘1’
memory: 512M
reservations:
cpus: ‘0.5’
memory: 256M
healthcheck:
test: [“CMD”, “node”, “-e”, “require(‘http’).get(‘http://localhost:3000/health’, (r) => {process.exit(r.statusCode === 200 ? 0 : 1)})”]
interval: 30s
timeout: 10s
retries: 3
start_period: 40s

mongodb:
image: mongo:6.0
container_name: ecommerce-mongodb
ports:
– “27017:27017”
volumes:
– mongodb_data:/data/db
– ./init-mongo.js:/docker-entrypoint-initdb.d/init-mongo.js:ro
environment:
– MONGO_INITDB_ROOT_USERNAME=admin
– MONGO_INITDB_ROOT_PASSWORD=${MONGO_PASSWORD}
– MONGO_INITDB_DATABASE=myapp
restart: unless-stopped
deploy:
resources:
limits:
memory: 1G

redis:
image: redis:7-alpine
container_name: ecommerce-redis
ports:
– “6379:6379”
volumes:
– redis_data:/data
command: redis-server –appendonly yes –requirepass ${REDIS_PASSWORD}
restart: unless-stopped
deploy:
resources:
limits:
memory: 256M

# API Gateway
gateway:
build:
context: .
dockerfile: Dockerfile.gateway
container_name: ecommerce-gateway
ports:
– “8000:8000”
environment:
– NODE_ENV=production
– JWT_SECRET=${JWT_SECRET}
depends_on:
– app
restart: unless-stopped

volumes:
mongodb_data:
redis_data:

networks:
default:
name: ecommerce-network
Nginx反向代理配置:
# nginx.conf
events {
worker_connections 1024;
}

http {
upstream backend {
least_conn;
server app:3000 max_fails=3 fail_timeout=30s;
# 可以添加多个实例实现负载均衡
# server app2:3000 max_fails=3 fail_timeout=30s;
}

upstream gateway {
server gateway:8000;
}

# 限流配置
limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;
limit_req_zone $binary_remote_addr zone=auth:10m rate=2r/s;

server {
listen 80;
server_name api.yourdomain.com;

# 安全头
add_header X-Frame-Options “SAMEORIGIN” always;
add_header X-Content-Type-Options “nosniff” always;
add_header X-XSS-Protection “1; mode=block” always;

# 健康检查(不经过限流)
location /health {
proxy_pass http://backend;
access_log off;
}

# 认证接口(严格限流)
location /api/auth {
limit_req zone=auth burst=5 nodelay;
proxy_pass http://backend;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}

# API接口(通用限流)
location /api/ {
limit_req zone=api burst=20 nodelay;
proxy_pass http://backend;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;

# 超时设置
proxy_connect_timeout 5s;
proxy_send_timeout 60s;
proxy_read_timeout 60s;
}

# 网关接口
location /gateway/ {
proxy_pass http://gateway/;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}

# 错误页面
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
}
}
六、性能测试与优化验证
6.1 使用Artillery进行负载测试
安装Artillery:
npm install -g artillery
测试脚本:
# load-test.yml
config:
target: ‘http://localhost:3000’
phases:
– duration: 60
arrivalRate: 10
name: Warm up
– duration: 120
arrivalRate: 50
name: Load test
– duration: 60
arrivalRate: 100
name: Stress test
plugins:
ensure: {}
ensure:
thresholds:
– http.response_time.p99: 1000
– http.response_time.p95: 500
– http.response_time.p50: 200
– http.requests: 10000

scenarios:
– name: “User authentication”
weight: 20
flow:
– post:
url: “/api/auth/register”
json:
email: “{{ $randomString }}@test.com”
password: “Test1234!”
name: “Test User”
capture:
– json: “$.token”
as: “authToken”
– think: 1
– get:
url: “/api/auth/me”
headers:
Authorization: “Bearer {{ authToken }}”

– name: “Browse products”
weight: 50
flow:
– get:
url: “/api/products?page=1&limit=20”
– think: 0.5
– get:
url: “/api/products/{{ $randomNumber(1, 100) }}”

– name: “Create order”
weight: 30
flow:
– post:
url: “/api/auth/login”
json:
email: “test@example.com”
password: “Test1234!”
capture:
– json: “$.token”
as: “authToken”
– get:
url: “/api/products”
headers:
Authorization: “Bearer {{ authToken }}”
capture:
– json: “$.products[0]._id”
as: “productId”
– post:
url: “/api/orders”
headers:
Authorization: “Bearer {{ authToken }}”
json:
items:
– productId: “{{ productId }}”
quantity: 2
price: 29.99
shippingAddress: “123 Main St”
运行测试:
artillery run –output report.json load-test.yml
artillery report report.json
6.2 使用Clinic.js进行性能分析
安装和使用:
npm install -g clinic

# 启动应用并分析
clinic doctor –on-port ‘autocannon localhost:3000’ — node src/server.js

# 生成火焰图
clinic flame –on-port ‘autocannon localhost:3000’ — node src/server.js

# 交互式分析
clinic heapprofiler –on-port ‘autocannon localhost:3000’ — node src/server.js
6.3 性能优化检查清单
代码层面:
[ ] 使用异步I/O,避免同步操作
[ ] 使用流处理大文件
[ ] 使用连接池管理数据库连接
[ ] 实现缓存策略(Redis)
[ ] 使用Worker Threads处理CPU密集型任务
[ ] 避免在循环中创建函数
[ ] 使用对象池减少GC压力
[ ] 及时清理事件监听器
架构层面:
[ ] 使用集群模式充分利用多核CPU
[ ] 实现负载均衡
[ ] 使用PM2进行进程管理
[ ] 实现断路器模式
[ ] 使用消息队列解耦异步任务
[ ] 实现API网关
[ ] 使用微服务架构(复杂系统)
监控层面:
[ ] 实现请求日志
[ ] 监控事件循环延迟
[ ] 监控内存使用
[ ] 监控CPU使用率
[ ] 监控数据库查询性能
[ ] 设置告警阈值
[ ] 使用APM工具(如New Relic)
部署层面:
[ ] 使用Docker容器化
[ ] 使用Kubernetes编排(大规模)
[ ] 实现CI/CD流水线
[ ] 配置Nginx反向代理
[ ] 启用Gzip压缩
[ ] 配置HTTP/2
[ ] 使用CDN加速静态资源
七、总结与最佳实践
7.1 核心原则
异步优先
:始终使用异步API,避免阻塞事件循环
错误处理
:所有异步操作都要有错误处理
资源管理
:及时释放连接、监听器等资源
监控驱动
:没有监控就没有优化
渐进式优化
:先测量,再优化,再测量
7.2 性能优化黄金法则
80/20法则
:优化最频繁使用的20%代码
缓存为王
:合理使用缓存可以提升10-100倍性能
减少I/O
:I/O是性能瓶颈的主要来源
水平扩展
:单机性能有限,学会横向扩展
异步处理
:将耗时操作异步化
7.3 持续改进
Node.js生态系统在快速发展,建议:
关注Node.js官方博客的更新
定期更新依赖包,修复安全漏洞
参与社区,学习最佳实践
定期进行代码审查和性能测试
建立性能基准,持续监控改进效果
通过本文的指南,你应该能够:
深入理解Node.js异步编程模型
掌握性能优化的核心技术
构建高可用的生产级系统
实现监控和容错机制
使用现代工具链进行开发和部署
记住,优秀的Node.js应用不是一蹴而就的,需要在实践中不断迭代和优化。保持学习,保持好奇,你的Node.js之旅将充满成就感!