【发布时间】:2020-05-05 06:15:30
【问题描述】:
我正在向我的 Laravel 应用程序路由添加缓存。我有一个在我的网站上呈现博客文章的功能:
public function show(Post $post)
{
SEO::setTitle($post->title);
SEO::setDescription($post->subtitle);
SEO::setCanonical('https://employbl.com/blog/' . $post->slug);
SEO::opengraph()->setUrl('https://employbl.com/blog/' . $post->slug);
SEO::opengraph()->addProperty('type', 'article');
SEO::opengraph()->addImage($post->featured_image);
SEO::twitter()->setSite('@Employbl_Jobs');
$markdown = Markdown::parse($post->body);
return view('blog.post', compact('post', 'markdown'));
}
这是调用该方法的路由:Route::get('/blog/{post}', 'PostController@show')->name('posts.show');,这样我的博客就会呈现一个带有类似以下内容的 URL:https://employbl.com/blog/laravel-vue-tailwindcss-single-page-application-spa
在此路由上实现缓存以便用户更快地加载页面的最佳方法是什么?
会不会是这样的:
$post = Cache::rememberForever('blog-post' . $post->id, function(){
return $post;
});
或者路由模型绑定是否需要缓存?缓存键是否需要唯一,或者我可以只使用“博客文章”作为缓存键吗?缓存$markdown 变量而不是$post 变量会更好吗?两者都有?
【问题讨论】:
-
取决于您要缓存的内容,如果是静态内容,您可能希望缓存整个页面内容
-
是的,它是存储在
posts表中的静态内容。为上述方法缓存整个页面内容的最佳方法是什么? -
好吧,我不知道缓存数据库可以执行的最简单查询之一(通过主键检索记录)获得了多少性能改进,但您也可以尝试缓存完整的 html 内容。我相信我曾经看过一个这样做的包裹。基本上它是一个缓存最终的
response的中间件,如果它已经被缓存,则立即返回它。
标签: php laravel laravel-5 caching