所以我试图在我的一个控制器上缓存一个查询,在大约12-19秒内返回大约3万条记录,这显然是不可接受的。我正在尝试集成基本的缓存,尽管我看到缓存的文件在加载页面后出现在项目中,但我加载结果的时间仍然不变。有人知道为什么会这样吗?我对Laravel还比较陌生——这种缓存应该在其他地方吗?我也看到了各种在路由级别缓存的例子。
public function index()
{
$questions = Cache::remember('questions', 60*60*24, function() {
return Question::with('tags')
->orderBy('updated_at', 'desc')
->with('exams.class')
->with('assignment.course')
->get();
});
$archived_questions = Cache::remember('archived-questions', 60*60*24, function() {
return Question::onlyTrashed()->with('tags')
->orderBy('deleted_at', 'desc')
->get();
});
return view('admin.index', ['questions' => $questions, 'archivedQuestions' => $archived_questions]);
}
您为每个索引操作设置了一个缓存,这意味着每次加载页面时,您都会重新运行该查询并将其分配给缓存
试试这个,
public function index()
{
if (Cache::has('questions')) {
$questions = Cache::get('questions');
} else {
$questions = Cache::remember('questions', 60*60*24, function() {
return Question::with('tags')
->orderBy('updated_at', 'desc')
->with('exams.class')
->with('assignment.course')
->get();
});
}
if (Cache::has('archivedQuestions')) {
$archivedQuestions= Cache::get('archivedQuestions');
} else {
$archived_questions = Cache::remember('archived-questions', 60*60*24, function() {
return Question::onlyTrashed()->with('tags')
->orderBy('deleted_at', 'desc')
->get();
});
}
return view('admin.index', ['questions' => $questions, 'archivedQuestions' => $archived_questions]);
}
看看这些文档;https://laravel.com/docs/8.x/cache特别是"从缓存中检索项目">