在午夜缓存数据库查询?

时间:2017-02-25 06:19:51

标签: php laravel caching redis

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

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

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

此时,缓存将在午夜过期,但第一个在早上通过此方法的人将是不幸的,必须执行查询,所以我想再次在午夜缓存所有这些查询。有一个简单的解决方案吗?或者我必须在晚上手动模仿http到服务器的呼叫吗?

1 个答案:

答案 0 :(得分:2)

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

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 - &gt; $命令:

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
相关问题