2017-02-25 29 views
0

我使用Redis的與laravel組合緩存在我的應用程序有些沉重疑問是這樣的:在午夜時間緩存數據庫查詢?

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

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

此時,緩存過期午夜,但在早晨通過這個方法的第一人將是不幸的,必須執行查詢,所以我想再次在午夜緩存所有這些查詢。有沒有簡單的解決方案?或者我將不得不在晚上手動模擬http呼叫到服務器?

+0

的cronjob調用頁面出了問題? –

+0

絕對是一種選擇。 – vincent

回答

1

一個實現你要找的東西的好方法是使用一個在午夜執行的調度程序來加熱緩存。

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

首先,使用PHP的工匠打造的命令:

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請求查詢頁面。

然後將它添加到應用程序/控制檯/內核 - > $命令:

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

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

此外,使得它執行在mignight此添加到應用程序/控制檯\內核調度()函數

最後,確保你已經設置了將執行laravel調度的crontask:

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

完美答案。 Tyvm – vincent