萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 依 URL 自動生成縮圖並解決高併發衝突:原理、實作與鎖機制

兩種縮圖生成時機比較

策略優點缺點
上傳時生成讀取零延遲、CPU 壓力分散尺寸變更需重新生成所有歷史圖片、儲存空間佔用大
訪問時生成按需生成、尺寸調整無需遷移、節省空間首次訪問延遲、高併發下重複生成衝突

現代架構多採用 訪問時生成 + CDN 快取,核心挑戰在於解決高併發下的「重複生成」與「資源爭搶」。

高併發衝突場景

100 個並發請求同時訪問不存在的 /thumb/200x200/photo.jpg:

  1. 所有請求檢測檔案不存在
  2. 全部進入生成邏輯
  3. CPU 飆升、磁碟 IO 爭搶、可能產生損壞檔案
  4. 甚至觸發 OOM 或磁碟寫滿

解決方案:原子性「處理中」標記鎖

核心邏輯

  1. 檢查目標縮圖是否存在 → 存在直接輸出
  2. 不存在 → 嘗試建立「處理中」標記檔(原子操作)
  3. 建立成功 → 當前進程負責生成,生成後刪除標記、輸出圖片
  4. 建立失敗(標記已存在) → 進入等待迴圈,輪詢標記消失 → 輸出生成好的檔案
  5. 設定等待超時,防止死鎖

完整實作代碼

<?php
// createthumb.php - 縮圖生成入口
declare(strict_types=1);

require_once __DIR__ . '/../config.php'; // 定義常數
require_once __DIR__ . '/PicThumb.class.php';
require_once __DIR__ . '/ThumbConfig.php';

$logFile = LOGS_DIR . '/createthumb.log';
$sourceBase = UPLOAD_DIR . '/original/';
$destBase   = UPLOAD_DIR . '/thumb/';

$relPath = $_GET['path'] ?? '';
if (!$relPath) exit('Missing path');

// 解析類型與配置
$type = explode('/', $relPath)[0];
$config = $thumbConfig[$type] ?? null;
if (!$config || empty($config['fromdir'])) exit('Invalid type');

$sourceFile = $sourceBase . $config['fromdir'] . '/' . substr($relPath, strlen($type) + 1);
$destFile   = $destBase . $relPath;

if (!file_exists($sourceFile)) {
    http_response_code(404);
    exit('Source not found');
}

// ===== 高併發鎖機制 =====
$lockFile = sys_get_temp_dir() . '/thumb_lock_' . md5($destFile);
$lockAcquired = false;
$waitTimeout = 10; // 秒
$startWait = time();

if (!file_exists($lockFile)) {
    // 嘗試原子建立:file_put_contents + LOCK_EX 非完全原子,但實務足夠
    // 更嚴謹可用 symlink() 或 mkdir() 原子性
    $lockAcquired = @file_put_contents($lockFile, getmypid(), LOCK_EX) !== false;
} 

if (!$lockAcquired) {
    // 等待其他進程生成完成
    while (file_exists($lockFile)) {
        if (time() - $startWait > $waitTimeout) {
            http_response_code(504);
            exit('Generation timeout');
        }
        usleep(200000); // 200ms
    }
    // 鎖釋放,檔案應已生成
    if (file_exists($destFile)) {
        outputImage($destFile);
    } else {
        http_response_code(500);
        exit('Generation failed');
    }
    exit;
}

// ===== 當前進程負責生成 =====
try {
    // 確保目標目錄存在
    $destDir = dirname($destFile);
    if (!is_dir($destDir)) mkdir($destDir, 0755, true);
    
    $thumb = new PicThumb($logFile);
    $thumb->setConfig($config);
    $success = $thumb->createThumb($sourceFile, $destFile);
    
    if ($success && file_exists($destFile)) {
        outputImage($destFile);
    } else {
        http_response_code(500);
        error_log("Thumb generation failed: $sourceFile -> $destFile");
    }
} finally {
    // 釋放鎖
    @unlink($lockFile);
}

function outputImage(string $file): never {
    ob_clean(); // 清除可能的輸出緩衝
    header('Content-Type: ' . mime_content_type($file));
    header('Content-Length: ' . filesize($file));
    header('Cache-Control: public, max-age=31536000, immutable'); // 長期快取
    readfile($file); // 高效輸出
    exit;
}

鎖機制進階:使用 symlink 原子性

file_put_contents 非完全原子(極罕見競態)。symlink() 在 POSIX 系統是原子操作,更適合做分散式鎖:

function acquireLock(string $lockFile): bool {
    $tmp = $lockFile . '.tmp.' . random_bytes(8);
    @symlink('/proc/self', $tmp); // 嘗試建立符號連結
    if (file_exists($tmp)) {
        // 重命名為正式鎖檔(rename 同檔案系統原子)
        @rename($tmp, $lockFile);
        return true;
    }
    return false;
}

function releaseLock(string $lockFile): void {
    @unlink($lockFile);
}

生產級架構建議

1. CDN 前置 + 回源觸發生成

# Nginx 設定
location /thumb/ {
    try_files $uri @generate_thumb;
}

location @generate_thumb {
    proxy_pass https://backend/generate_thumb.php;
    proxy_set_header X-Original-URI $request_uri;
}

2. 異步生成佇列(極高併發)

  • 請求發現無縮圖 → 推送生成任務到 Redis/RabbitMQ → 立即回傳「處理中」佔位圖
  • Worker 消費任務生成縮圖 → 完成後通知前端輪詢或 WebSocket 推送
  • 避免 HTTP 請求長時間持有連線

3. 物件儲存 + 影像處理服務

  • S3 / MinIO + Lambda / CloudFunction 觸發縮圖生成
  • Imgix、Cloudinary、Thumbor 等專用影像服務

PicThumb.class.php 關鍵配置參考

// ThumbConfig.php
$thumbConfig = [
    'avatar' => [
        'fromdir' => 'avatars',
        'width' => 200,
        'height' => 200,
        'mode' => 'crop', // crop/fit/stretch
        'quality' => 85,
    ],
    'article' => [
        'fromdir' => 'articles',
        'width' => 800,
        'height' => 600,
        'mode' => 'fit',
        'quality' => 80,
    ],
];

監控與告警指標

  • 縮圖生成平均耗時
  • 鎖等待次數 / 平均等待時間
  • 生成失敗率
  • 磁碟使用量增長趨勢

總結

「訪問時生成 + 原子鎖 + CDN 快取」是兼顧彈性與效能的經典方案。關鍵在於:鎖粒度細(單檔)、等待超時保護、生成成功才釋放鎖、失敗不留殘檔。極高併發下建議升級為異步佇列或專用影像服務。

copyright © 萬盛學電腦網 all rights reserved