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

标签 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 调用?

最佳答案

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

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/

相关文章:

php - 用 PHP 访问 MySQL 字段的 Comments

php - 从 PHP 脚本发送多封电子邮件

php - PHP/MySQL 的隐私选项

php - 将值推送到 Laravel 中的现有缓存值

java - 如何清除 Java 缓存中的特定文件?

php - 在 PHP 中获取上传文件扩展名的最佳方法/实践是什么

Laravel 5 路由模型绑定(bind)在服务器上不起作用

phpunit - 测试新模型时未找到 Eloquent 类

ios - 在 iOS APP 中删除 ~/Library/Caches 中的 Fabric 内容是否安全

c++ - 如何缓存 1000 个大型 C++ 对象