我正在尝试将带有参数的整个刀片视图存储在缓存中以进行首次加载,并在下次重新加载时从缓存中加载它。
这是我所做的:
public function cacheAction()
{
$data = $this->model->getContent();
Cache::remember('cache-view', 1800, function() {
dd('load from cache!');
return view('index')->render();
});
dd('not load from cache!');
return view('index', ['data' => $data]);
}
我在加载页面时添加了 2 行调试通知。但是当我访问页面时,它总是显示“未从缓存中加载!” 随时。
我该如何解决这个问题?
非常感谢你!
你在这里有相反的方式。当remember
回调中的函数运行时,它不会从缓存中加载。当它不运行时,它会从缓存中加载。但是,您实际上并没有在此处使用缓存中的结果。您可以执行以下操作来利用缓存:
public function cacheAction()
{
$view = Cache::remember('cache-view', 1800, function() {
$data = $this->model->getContent();
return view('index', ['data' => $data]);
});
return $view;
}
请注意,您的cache-view
缓存键实际上并不依赖于内容,$data
因此如果$data
更改,您将获得陈旧的缓存视图。以下是解决此问题的方法:
public function cacheAction()
{
$data = $this->model->getContent();
$cacheKey = md5(serialize($data)); // Make sure data is serializable
$view = Cache::remember('cache-view-'.$cacheKey, 1800, function() use ($data) {
return view('index', ['data' => $data]);
});
return $view;
}
然而,这确实具有总是读取$data
以检查缓存是否陈旧的缺点。哪种解决方案适合您,取决于您的数据是静态的还是动态的。如果您不希望数据经常更改,那么人们看到最多 1800 秒的陈旧数据可能不是一个大问题
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句