我正在使用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->$命令:
protected $commands = [
    // ...
    \App\Console\Commands\WarmCache::class,
    // ...
];

另外,将其添加到app/console\kernel schedule()函数中,以便它在mignight执行:
$schedule->command('warmcache')->daily();

最后,确保设置了执行laravel调度程序的crontask:
* * * * * php /path/to/artisan schedule:run >> /dev/null 2>&1

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

10-14 15:15
查看更多