gpt4 book ai didi

php - 在午夜缓存数据库查询?

转载 作者:可可西里 更新时间:2023-11-01 11:13:05 25 4
gpt4 key购买 nike

我将 Redis 与 laravel 结合使用,以在我的应用程序中缓存一些繁重的查询,如下所示:

return Cache::remember('projects.wip', $this->cacheDuration(), function () {
...
});

private function cacheDuration()
{
return Carbon::now()->endOfDay()->diffInSeconds(Carbon::now());
}

此刻,缓存在午夜过期,但早上第一个通过此方法的人将是必须执行查询的不幸者,因此我想在午夜再次缓存所有这些查询。有一个简单的解决方案吗?还是我必须在晚上手动模拟对服务器的 http 调用?

最佳答案

实现您正在寻找的目标的一个好方法是使用在午夜执行的调度程序来预热缓存。

https://laravel.com/docs/5.4/scheduling

首先,使用php artisan创建命令:

php artisan make:command WarmCache

您应该对其进行编辑,使其看起来像这样:

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;

class WarmCache extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'warmcache';

/**
* The console command description.
*
* @var string
*/
protected $description = 'Warms Cache';

/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}

/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
// >>>> INSERT YOUR CACHE CODE HERE <<<<
}
}

您应该在 handle() 函数中添加预热缓存的代码,这取决于您尝试缓存的内容,您可能不需要发出 http 请求。但是,如果需要,您始终可以使用 curl 或 guzzle 之类的工具将页面作为 http 请求进行查询。

然后将其添加到 app/Console/Kernel -> $commands:

protected $commands = [
// ...
\App\Console\Commands\WarmCache::class,
// ...
];

此外,将此添加到 app/Console\Kernel schedule() 函数,以便它在午夜执行:

$schedule->command('warmcache')->daily();

最后,确保您已经设置了将执行 laravel 调度程序的 crontask:

* * * * * php /path/to/artisan schedule:run >> /dev/null 2>&1

关于php - 在午夜缓存数据库查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42452691/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com