{T}

伸缩性架构 学习笔记(第 4 部分)

4.4 Kubernetes 伸缩策略

水平伸缩 vs 垂直伸缩

code
伸缩方式对比:

水平伸缩 (Horizontal Scaling)
├── 方式:增加 Pod 数量
├── 优势:线性扩展、无上限
├── 劣势:需要负载均衡、状态管理复杂
└── 实现:HPA (Horizontal Pod Autoscaler)

垂直伸缩 (Vertical Scaling)
├── 方式:增加 Pod 资源(CPU、内存)
├── 优势:实现简单、无状态管理问题
├── 劣势:有上限、需要重启 Pod
└── 实现:VPA (Vertical Pod Autoscaler)

自动伸缩实现代码

javascript
// Kubernetes 自动伸缩监控实现
class AutoScaler {
  constructor(k8sClient) {
    this.client = k8sClient
    this.metricsServer = new MetricsServer()
  }
  
  // 监控 CPU 使用率并自动伸缩
  async monitorAndScale(deploymentName, namespace = 'default') {
    // 1. 获取当前指标
    const metrics = await this.metricsServer.getMetrics(deploymentName, namespace)
    
    // 2. 获取当前 Pod 数量
    const deployment = await this.client.apis.apps.v1
      .namespaces(namespace)
      .deployments(deploymentName)
      .get()
    
    const currentReplicas = deployment.body.spec.replicas
    
    // 3. 计算目标副本数
    const cpuUtilization = metrics.cpu.current / metrics.cpu.request
    const targetUtilization = 0.7  // 目标 CPU 使用率 70%
    
    let targetReplicas = Math.ceil(currentReplicas * (cpuUtilization / targetUtilization))
    
    // 限制在最小和最大副本数之间
    targetReplicas = Math.max(2, Math.min(targetReplicas, 10))
    
    // 4. 执行伸缩
    if (targetReplicas !== currentReplicas) {
      await this.scaleDeployment(deploymentName, namespace, targetReplicas)
      console.log(`Scaled ${deploymentName} from ${currentReplicas} to ${targetReplicas} replicas`)
    }
  }
  
  // 执行伸缩操作
  async scaleDeployment(name, namespace, replicas) {
    await this.client.apis.apps.v1
      .namespaces(namespace)
      .deployments(name)
      .patch({
        body: {
          spec: {
            replicas: replicas
          }
        }
      })
  }
  
  // 启动自动伸缩监控
  startMonitoring(deploymentName, interval = 60000) {
    setInterval(async () => {
      try {
        await this.monitorAndScale(deploymentName)
      } catch (error) {
        console.error('Auto-scaling error:', error)
      }
    }, interval)
  }
}

// 使用示例
const k8sClient = require('kubernetes-client').Client
const autoScaler = new AutoScaler(new k8sClient())
autoScaler.startMonitoring('frontend-deployment', 60000)  // 每分钟检查一次

五、容器编排能力详解

5.1 容器编排的定义

容器编排:管理容器全生命周期的过程,包括部署、调度、伸缩、网络、存储等。