{T}

高性能架构 学习笔记(第 4 部分)

5.2 性能监控代码实现

javascript
// 性能监控中间件
class PerformanceMonitor {
  constructor() {
    this.metrics = {
      requests: [],
      transactions: []
    }
  }
  
  // 记录请求(QPS/RPS)
  recordRequest(req, res, next) {
    const startTime = Date.now()
    
    res.on('finish', () => {
      const duration = Date.now() - startTime
      
      this.metrics.requests.push({
        path: req.path,
        method: req.method,
        duration,
        timestamp: startTime
      })
    })
    
    next()
  }
  
  // 记录事务(TPS)
  recordTransaction(transactionName, callback) {
    const startTime = Date.now()
    
    return async (...args) => {
      try {
        const result = await callback(...args)
        
        const duration = Date.now() - startTime
        this.metrics.transactions.push({
          name: transactionName,
          duration,
          timestamp: startTime,
          status: 'success'
        })
        
        return result
      } catch (error) {
        const duration = Date.now() - startTime
        this.metrics.transactions.push({
          name: transactionName,
          duration,
          timestamp: startTime,
          status: 'failed'
        })
        
        throw error
      }
    }
  }
  
  // 计算实时 QPS
  getQPS(windowMs = 60000) {
    const now = Date.now()
    const windowStart = now - windowMs
    
    const recentRequests = this.metrics.requests.filter(
      req => req.timestamp >= windowStart
    )
    
    return recentRequests.length / (windowMs / 1000)
  }
  
  // 计算实时 TPS
  getTPS(windowMs = 60000) {
    const now = Date.now()
    const windowStart = now - windowMs
    
    const recentTransactions = this.metrics.transactions.filter(
      tx => tx.timestamp >= windowStart
    )
    
    return recentTransactions.length / (windowMs / 1000)
  }
  
  // 获取性能报告
  getPerformanceReport() {
    return {
      qps: this.getQPS(),
      tps: this.getTPS(),
      avgResponseTime: this.getAverageResponseTime(),
      totalRequests: this.metrics.requests.length,
      totalTransactions: this.metrics.transactions.length
    }
  }
  
  // 计算平均响应时间
  getAverageResponseTime() {
    if (this.metrics.requests.length === 0) return 0
    
    const totalDuration = this.metrics.requests.reduce(
      (sum, req) => sum + req.duration, 0
    )
    
    return totalDuration / this.metrics.requests.length
  }
}
 
// 使用示例
const monitor = new PerformanceMonitor()
 
// 记录请求
app.use(monitor.recordRequest)
 
// 记录事务
const createOrder = monitor.recordTransaction('createOrder', async (orderData) => {
  // 订单创建逻辑
  const order = await Order.create(orderData)
  return order
})
 
// 定时输出性能报告
setInterval(() => {
  const report = monitor.getPerformanceReport()
  console.log('Performance Report:', report)
}, 60000)  // 每分钟输出一次

5.3 Prometheus + Grafana 监控

yaml
# prometheus.yml 配置
global:
  scrape_interval: 15s
 
scrape_configs:
  - job_name: 'nodejs-app'
    static_configs:
      - targets: ['localhost:3000']
javascript
// Node.js 应用集成 Prometheus
const client = require('prom-client')
 
// 创建指标
const httpRequestDuration = new client.Histogram({
  name: 'http_request_duration_seconds',
  help: 'Duration of HTTP requests in seconds',
  labelNames: ['method', 'route', 'status_code'],
  buckets: [0.1, 0.5, 1, 1.5, 2, 5]
})
 
const qpsCounter = new client.Counter({
  name: 'http_requests_total',
  help: 'Total number of HTTP requests',
  labelNames: ['method', 'route']
})
 
// 中间件
app.use((req, res, next) => {
  const start = Date.now()
  
  res.on('finish', () => {
    const duration = (Date.now() - start) / 1000
    
    httpRequestDuration
      .labels(req.method, req.route, res.statusCode)
      .observe(duration)
    
    qpsCounter
      .labels(req.method, req.route)
      .inc()
  })
  
  next()
})
 
// 暴露指标接口
app.get('/metrics', async (req, res) => {
  res.set('Content-Type', client.register.contentType)
  res.end(await client.register.metrics())
})

六、性能测试方法