在laravel項(xiàng)目中集成阿里云的視頻點(diǎn)播服務(wù)時, 需要上傳視頻后獲取視頻時長,由于視頻時長并不是能馬上獲取到的參數(shù)(應(yīng)該是在阿里云視頻轉(zhuǎn)碼之后才能得到), 什么時候能獲取到并不確定, 因此考慮使用laravel的隊(duì)列服務(wù)來延遲獲取.
<?php
namespace App\Jobs;
use App\Models\Video;
use App\Service\AliVod;
use Carbon\Carbon;
use Illuminate\Bus\Queueable;
/**
* 上傳后獲取視頻長度
* Class GetVideoDuration
* @package App\Jobs
*/
class GetVideoDuration extends Job
{
use Queueable;
protected $video;
public function __construct($id)
{
$this->video = Video::find($id);
}
public function handle()
{
try {
$video_info = AliVod::get_video_info($this->video->video_id);
$duration = $video_info['Video']->Duration;
if (0 != $duration) {
$this->video->update([
'duration' => $duration
]);
\Log::info('獲取視頻時間成功, 視頻表id ==> ' . $this->video->id);
} else {
\Log::info('視頻時間為 0 , 視頻表id ==> ' . $this->video->id. ', 重新分發(fā)');
dispatch((new GetVideoDuration($this->video->id))->delay(Carbon::now()->addMinutes(3)));
}
} catch (\Exception $e) {
\Log::info('獲取視頻時間失敗, 視頻表id ==> ' . $this->video->id . ', 原因 : '. $e->getMessage() . ', 重新分發(fā)');
dispatch((new GetVideoDuration($this->video->id))->delay(Carbon::now()->addMinutes(3)));
}
}
}
期間遇到的問題是隊(duì)列第一次能正常運(yùn)行, 之后再次分發(fā)的話, 會一直報下面這個錯誤:
ErrorException: Undefined index: cn-shanghai#vod in /workspace/dev6/ctjy_api_server/app/Service/VodServer/aliyun-php-sdk-core/Regions/LocationService.php:82
找到報錯的阿里云的sdk的位置, 在這個方法前面加上代碼對這個變量進(jìn)行判斷
private function checkCacheIsExpire($key)
{
if(!self::$lastClearTimePerProduct) return false; // 加上代碼
$lastClearTime = self::$lastClearTimePerProduct[$key];
if ($lastClearTime == null)
{
$lastClearTime = time();
self::$lastClearTimePerProduct[$key] = $lastClearTime;
}
$now = time();
$elapsedTime = $now - $lastClearTime;
if ($elapsedTime > CACHE_EXPIRE_TIME)
{
$lastClearTime = time();
self::$lastClearTimePerProduct[$key] = $lastClearTime;
return true;
}
return false;
}