| 策略 | 優點 | 缺點 |
|---|---|---|
| 上傳時生成 | 讀取零延遲、CPU 壓力分散 | 尺寸變更需重新生成所有歷史圖片、儲存空間佔用大 |
| 訪問時生成 | 按需生成、尺寸調整無需遷移、節省空間 | 首次訪問延遲、高併發下重複生成衝突 |
現代架構多採用 訪問時生成 + CDN 快取,核心挑戰在於解決高併發下的「重複生成」與「資源爭搶」。
100 個並發請求同時訪問不存在的 /thumb/200x200/photo.jpg:
<?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;
}
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);
}
# 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;
}
// 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 快取」是兼顧彈性與效能的經典方案。關鍵在於:鎖粒度細(單檔)、等待超時保護、生成成功才釋放鎖、失敗不留殘檔。極高併發下建議升級為異步佇列或專用影像服務。