程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 網頁編程 >> PHP編程 >> 關於PHP編程 >> php 根據url自動生成縮略圖並處理高並發問題

php 根據url自動生成縮略圖並處理高並發問題

編輯:關於PHP編程

服務器生成縮略圖的時機一般分為兩種:

1.上傳文件時生成

優點:上傳時就已經生成需要的縮略圖,讀取時不需要再判斷,減少cpu運算。

缺點:當縮略圖尺寸變化時或新增尺寸時,需要重新生成所有的縮略圖。

2.訪問時生成

優點:1.當有用戶訪問時才需要生成,沒有訪問的不用生成,節省空間。

2.當修改縮略圖尺寸時,只需要修改設置,無需重新生成所有縮略圖。

缺點:當縮略圖不存在需要生成時,高並發訪問會非常耗服務器資源。

雖然訪問時生成會有高並發問題,但其他優點都比第一種方法好,因此只要解決高並發問題就可以。

關於如何根據url自動生成縮略圖的原理及實現,可以參考我之前寫的《php 根據url自動生成縮略圖》。

高並發處理原理:

1.當判斷需要生成圖片時,在tmp/目錄創建一個臨時標記文件,文件名用md5(需要生成的文件名)來命名,處理結束後再將臨時文件刪除。

2.當判斷要生成的文件在tmp/目錄有臨時標記文件,表示文件正在處理中,則不調用生成縮略圖方法,而等待,直到臨時標記文件被刪除,生成成功輸出。

修改的文件如下,其他與之前一樣。

createthumb.php
復制代碼 代碼如下:
<?php
define('WWW_PATH', dirname(dirname(__FILE__))); // 站點www目錄

require(WWW_PATH.'/PicThumb.class.php'); // include PicThumb.class.php
require(WWW_PATH.'/ThumbConfig.php'); // include ThumbConfig.php

$logfile = WWW_PATH.'/createthumb.log'; // 日志文件
$source_path = WWW_PATH.'/upload/'; // 原路徑
$dest_path = WWW_PATH.'/supload/'; // 目標路徑

$path = isset($_GET['path'])? $_GET['path'] : ''; // 訪問的圖片URL

// 檢查path
if(!$path){
exit();
}

// 獲取圖片URI
$relative_url = str_replace($dest_path, '', WWW_PATH.$path);

// 獲取type
$type = substr($relative_url, 0, strpos($relative_url, '/'));

// 獲取config
$config = isset($thumb_config[$type])? $thumb_config[$type] : '';

// 檢查config
if(!$config || !isset($config['fromdir'])){
exit();
}

// 原圖文件
$source = str_replace('/'.$type.'/', '/'.$config['fromdir'].'/', $source_path.$relative_url);

// 目標文件
$dest = $dest_path.$relative_url;

if(!file_exists($source)){ // 原圖不存在
exit();
}

// 高並發處理
$processing_flag = '/tmp/thumb_'.md5($dest); // 用於判斷文件是否處理中
$is_wait = 0; // 是否需要等待
$wait_timeout = 5; // 等待超時時間

if(!file_exists($processing_flag)){
file_put_contents($processing_flag, 1, true);
}else{
$is_wait = 1;
}

if($is_wait){ // 需要等待生成
while(file_exists($processing_flag)){
if(time()-$starttime>$wait_timeout){ // 超時
exit();
}
usleep(300000); // sleep 300 ms
}

if(file_exists($dest)){ // 圖片生成成功
ob_clean();
header('content-type:'.mime_content_type($dest));
exit(file_get_contents($dest));
}else{
exit(); // 生成失敗退出
}
}

// 創建縮略圖
$obj = new PicThumb($logfile);
$obj->set_config($config);
$create_flag = $obj->create_thumb($source, $dest);

unlink($processing_flag); // 刪除處理中標記文件

if($create_flag){ // 判斷是否生成成功
ob_clean();
header('content-type:'.mime_content_type($dest));
exit(file_get_contents($dest));
}

?>

源碼下載地址:點擊查看

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved