電商大促常需營造「搶購火爆」氛圍。本文設計一個可控概率的「系統繁忙」模擬算法,核心思路:構建固定比例的紅藍球池,每次請求前充分打亂,再隨機抽取決定是否放行。
<?php
/**
* 偽裝繁忙判斷
* @param float $busyRate 繁忙概率 0.0-1.0(預設 70%)
* @return bool true=繁忙 false=放行
*/
function pretendBusy($busyRate = 0.7) {
// 1. 初始化球池:3 紅(放行),7 藍(繁忙)
$total = 10;
$redCount = (int)($total * (1 - $busyRate));
$blueCount = $total - $redCount;
$balls = array_merge(array_fill(0, $redCount, 'red'), array_fill(0, $blueCount, 'blue'));
// 2. 充分打亂:隨機交換紅藍球 10 次
for ($i = 0; $i < 10; $i++) {
// 獲取隨機紅球索引
$redIndices = array_keys($balls, 'red');
$randRed = $redIndices[array_rand($redIndices)];
// 獲取隨機藍球索引
$blueIndices = array_keys($balls, 'blue');
$randBlue = $blueIndices[array_rand($blueIndices)];
// 交換
$tmp = $balls[$randRed];
$balls[$randRed] = $balls[$randBlue];
$balls[$randBlue] = $tmp;
}
// 3. 隨機抽取一個球
$result = $balls[array_rand($balls)];
return $result === 'blue'; // 藍球返回 true(繁忙)
}
// 使用示例
if (pretendBusy(0.7)) {
exit(json_encode(['code' => 503, 'msg' => '系統繁忙,請稍後再試']));
}
// 正常業務邏輯...
echo json_encode(['code' => 200, 'msg' => '搶購成功']);
?>
$busyRate 精確控制繁忙比例// ❌ 錯誤:固定順序數組 + rand(),概率不穩定 $arr = ['red','red','red','blue','blue','blue','blue','blue','blue','blue']; echo $arr[rand(0,9)]; // 每次請求數組順序固定,rand() 均勻分布但樣本空間有序,長期看偏離 70% // ❌ 錯誤:shuffle() 每次打亂整個數組,性能較差 shuffle($arr); echo $arr[0]; // 每次打亂 10 元素開銷大於定向交換紅藍球
$busyRate此算法以極低成本實現業務需求,避免了複雜分佈式鎖或限流組件的引入,適合中小型電商促銷場景。