Skip to content

Instantly share code, notes, and snippets.

@KangYoosam
Created February 6, 2020 08:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KangYoosam/74cf04cea5ab017078323774828fbe32 to your computer and use it in GitHub Desktop.
Save KangYoosam/74cf04cea5ab017078323774828fbe32 to your computer and use it in GitHub Desktop.
【Laravel】File管理していたsession情報をredisに移行するコマンド
<?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