From efcd29faa254757c075cd76eb9475004a195ec6a Mon Sep 17 00:00:00 2001 From: filesite Date: Sat, 5 Oct 2024 14:03:50 +0800 Subject: [PATCH] add cache-control and etag for video meta api --- conf/app.php | 2 ++ themes/beauty/controller/SiteController.php | 18 +++++++++++++++++- 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/conf/app.php b/conf/app.php index 99bf05f..41eff6e 100644 --- a/conf/app.php +++ b/conf/app.php @@ -64,6 +64,8 @@ $configs = array( 'small_image_client_cache_seconds' => 600, //目录封面图在浏览器端缓存时长,单位:秒 'dir_snapshot_client_cache_seconds' => 300, + //视频、音乐meta在浏览器端缓存时长,单位:秒 + 'meta_client_cache_seconds' => 300, //列表页缩略图尺寸设置 'small_image_min_width' => 360, //缩略图最小宽度设置,以确保清晰度 diff --git a/themes/beauty/controller/SiteController.php b/themes/beauty/controller/SiteController.php index 06ff718..c4cce41 100644 --- a/themes/beauty/controller/SiteController.php +++ b/themes/beauty/controller/SiteController.php @@ -805,6 +805,9 @@ Class SiteController extends Controller { $msg = 'OK'; $meta = array(); + $httpStatus = 200; + $customHeaders = array(); + $videoId = $this->get('id', ''); if (empty($videoId)) { $code = 0; @@ -816,13 +819,26 @@ Class SiteController extends Controller { $cachedData = Common::getCacheFromFile($cacheKey, $expireSeconds, $cacheSubDir); if (!empty($cachedData)) { $meta = $cachedData; + + //增加客户端缓存header + $etag = md5(json_encode($meta)); + $etag_from_client = !empty($_SERVER['HTTP_IF_NONE_MATCH']) ? $_SERVER['HTTP_IF_NONE_MATCH'] : ''; //get etag from client + if (!empty($etag) && $etag == $etag_from_client) { + $httpStatus = 304; + } + + $meta_client_cache_seconds = FSC::$app['config']['meta_client_cache_seconds']; + $customHeaders = array( + "Cache-Control: max-age={$meta_client_cache_seconds}", + "Etag: {$etag}", + ); }else { $code = 0; $msg = '此视频无缓存或缓存已过期'; } } - return $this->renderJson(compact('code', 'msg', 'meta')); + return $this->renderJson(compact('code', 'msg', 'meta'), $httpStatus, $customHeaders); } //保存视频meta数据到缓存,支持手动生成