优化文章详情缓存;

This commit is contained in:
2022-07-21 15:16:24 +08:00
parent da8b9b5e30
commit ec97f2d56a
2 changed files with 200 additions and 178 deletions

View File

@@ -5,6 +5,7 @@ declare(strict_types=1);
namespace app\index\controller; namespace app\index\controller;
use app\model\Post as ModelPost; use app\model\Post as ModelPost;
use think\facade\Cache;
use think\facade\View; use think\facade\View;
use think\model\Relation; use think\model\Relation;
use think\Request; use think\Request;
@@ -52,6 +53,12 @@ class Post extends Common
{ {
// //
$cache_key = 'post_' . $uid;
$model_post = Cache::get($cache_key);
if (empty($model_post)) {
$model_post = ModelPost::with([ $model_post = ModelPost::with([
'comments' => function (Relation $query) { 'comments' => function (Relation $query) {
$query->order('id asc'); $query->order('id asc');
@@ -62,6 +69,10 @@ class Post extends Common
return $this->error('链接已失效', '/'); return $this->error('链接已失效', '/');
} }
Cache::set($cache_key, $model_post);
}
$model_post->hits = $model_post->hits + 1; $model_post->hits = $model_post->hits + 1;
$model_post->save(); $model_post->save();

View File

@@ -4,7 +4,9 @@ declare(strict_types=1);
namespace app\index\controller; namespace app\index\controller;
use app\model\Post;
use app\model\PostComment as ModelPostComment; use app\model\PostComment as ModelPostComment;
use think\facade\Cache;
use think\facade\Session; use think\facade\Session;
use think\facade\Validate; use think\facade\Validate;
use think\Request; use think\Request;
@@ -57,8 +59,13 @@ class PostComment extends Common
return json_message($validate->getError()); return json_message($validate->getError());
} }
$post_data['type'] = 3; $model_post = Post::find($post_data['post_id']);
if (empty($model_post)) {
return json_message('文章不存在');
}
$post_data['type'] = 3;
$post_data['user_uid'] = $user_uid; $post_data['user_uid'] = $user_uid;
@@ -66,6 +73,10 @@ class PostComment extends Common
ModelPostComment::clearCountCache(); ModelPostComment::clearCountCache();
Cache::delete('post_' . $model_post->uid);
return json_message(); return json_message();
} }