一、每天固定时间点的秒杀活动
秒杀活动的特征是时间比较固定,可以在活动开始前提前扩容。
seckill.yaml 文件配置示例如下:
apiVersion: apps/v1kind: Deploymentmetadata: name: seckill labels: app: seckillspec: replicas: 3 selector: matchLabels: app: seckill template: metadata: labels: app: seckill spec: containers: – name: seckill image: nginx:1.21.6 ports: – containerPort: 80 resources: requests: memory: "256Mi" cpu: "250m" limits: memory: "512Mi" cpu: "500m"
ScaledObject.yaml 文件配置示例如下:
apiVersion: keda.sh/v1alpha1kind: ScaledObjectmetadata: name: seckillspec: scaleTargetRef: apiVersion: apps/v1 kind: Deployment name: seckill pollingInterval: 15 minReplicaCount: 2 # 至少保留 2 个副本 maxReplicaCount: 1000 advanced: horizontalPodAutoscalerConfig: behavior: # 控制扩缩容行为,使用比较保守的策略,快速扩容,缓慢缩容 scaleDown: # 缓慢缩容:至少冷却 10 分钟才能缩容 stabilizationWindowSeconds: 600 policies: – type: Percent value: 100 periodSeconds: 15 scaleUp: # 快速扩容:每 15s 最多允许扩容 5 倍 policies: – type: Percent value: 500 periodSeconds: 15 triggers: – type: cron # 每天早上 10 点秒杀活动,确保前后半小时内至少有 200 个副本 metadata: timezone: Asia/Shanghai start: 30 9 * * * end: 30 10 * * * desiredReplicas: "200" – type: cron # 每天晚上 6 点秒杀活动,确保前后半小时内至少有 200 个副本 metadata: timezone: Asia/Shanghai start: 30 17 * * * end: 30 18 * * * desiredReplicas: "200" – type: memory # 内存 利用率超过 60% 扩容 metricType: Utilization metadata: value: "60" – type: cpu # cpu利用率超过 60% 扩容 metricType: Utilization metadata: value: "60"
配置好seckill.yaml和 ScaledObject.yaml 后执行以下命令:
kubectl apply -f seckill.yamlkubectl apply -f ScaledObject.yaml
执行以下命令查询所有命名空间的 ScaledObject(KEDA 资源):
$ kubectl get scaledobject –all-namespaces NAMESPACE NAME SCALETARGETKIND SCALETARGETNAME MIN MAX READY ACTIVE FALLBACK PAUSED TRIGGERS AUTHENTICATIONS AGEdefault seckill apps/v1.Deployment seckill 2 1000 True True False Unknown cron,memory,cpu 14m
二、注意事项
通常情况下,触发器不能仅配置 Cron,还需要与其他触发器配合使用。因为如果在 Cron 的 start 和 end 区间之外的时间段,如果没有其它触发器活跃,副本数将会降到 minReplicaCount。