Created
February 6, 2020 08:32
-
-
Save KangYoosam/74cf04cea5ab017078323774828fbe32 to your computer and use it in GitHub Desktop.
【Laravel】File管理していたsession情報をredisに移行するコマンド
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Console\Commands; | |
use Illuminate\Console\Command; | |
use Illuminate\Support\Facades\Redis; | |
class MigrateSessionToRedisFromFile extends Command | |
{ | |
/** | |
* The name and signature of the console command. | |
* | |
* @var string | |
*/ | |
protected $signature = 'session:redis'; | |
/** | |
* The console command description. | |
* | |
* @var string | |
*/ | |
protected $description = 'File管理していたsession情報をredisに移行する'; | |
/** | |
* Create a new command instance. | |
* | |
* @return void | |
*/ | |
public function __construct() | |
{ | |
parent::__construct(); | |
} | |
/** | |
* Execute the console command. | |
* | |
* @return mixed | |
*/ | |
public function handle() | |
{ | |
$this->info('Starting session migration..'); | |
$sessions = $this->startMigration(); | |
$this->info('Finished session migration.'); | |
} | |
private function startMigration() | |
{ | |
$session_path = 'storage/framework/sessions/'; | |
$dh = opendir($session_path); | |
// sessionディレクトリを全て洗う | |
while ($file = readdir($dh)) { | |
// ファイル名が12文字以下のものはsession管理ファイル以外のものなので無視 | |
if (strlen($file) < 12) { | |
continue; | |
} | |
// sessionファイルの中身取得 | |
$content = file_get_contents($session_path.$file); | |
$valueForRedis = serialize($content); | |
// redisのkey生成 | |
$prefix = config('cache.prefix'); | |
$redis_key = $prefix.':'.$file; | |
// reidsにset | |
Redis::set($redis_key, $valueForRedis, 'EX', config('session.lifetime')); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment