{T}

高可用架构 学习笔记(第 4 部分)

javascript
// 灰度发布系统
class CanaryDeployment {
  constructor() {
    this.versions = {
      stable: { weight: 90, version: 'v1.0.0' },
      canary: { weight: 10, version: 'v2.0.0' }
    }
  }
  
  // 路由请求
  route(userId) {
    const hash = this.hashUserId(userId)
    const percentage = hash % 100
    
    if (percentage < this.versions.canary.weight) {
      return this.versions.canary.version
    } else {
      return this.versions.stable.version
    }
  }
  
  // 调整灰度比例
  adjustWeight(canaryWeight) {
    if (canaryWeight < 0 || canaryWeight > 100) {
      throw new Error('权重必须在 0-100 之间')
    }
    
    this.versions.canary.weight = canaryWeight
    this.versions.stable.weight = 100 - canaryWeight
    
    console.log(`灰度比例调整: 稳定版 ${this.versions.stable.weight}%, 灰度版 ${this.versions.canary.weight}%`)
  }
  
  // 监控灰度版本
  monitorCanary() {
    const metrics = {
      errorRate: this.getErrorRate('canary'),
      latency: this.getAverageLatency('canary'),
      throughput: this.getThroughput('canary')
    }
    
    // 自动回滚
    if (metrics.errorRate > 0.05) {
      console.log('灰度版本错误率过高,自动回滚')
      this.rollback()
    }
    
    return metrics
  }
  
  // 回滚
  rollback() {
    this.versions.canary.weight = 0
    this.versions.stable.weight = 100
    console.log('已回滚到稳定版本')
  }
  
  // 哈希用户 ID
  hashUserId(userId) {
    let hash = 0
    for (let char of String(userId)) {
      hash = (hash << 5) - hash + char.charCodeAt(0)
    }
    return Math.abs(hash)
  }
  
  // 获取错误率
  getErrorRate(version) {
    // 模拟数据
    return Math.random() * 0.1
  }
  
  // 获取平均延迟
  getAverageLatency(version) {
    return Math.random() * 100 + 50
  }
  
  // 获取吞吐量
  getThroughput(version) {
    return Math.floor(Math.random() * 1000 + 500)
  }
}
 
// 使用示例
const canary = new CanaryDeployment()
 
// 路由用户请求
const version1 = canary.route('user123')
console.log(`用户 user123 路由到版本: ${version1}`)
 
// 逐步扩大灰度范围
canary.adjustWeight(20)  // 20% 流量到灰度版本
 
// 监控灰度版本
const metrics = canary.monitorCanary()
console.log('灰度版本指标:', metrics)