Skip to content

Instantly share code, notes, and snippets.

@Apmyp
Last active June 29, 2020 10:08
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 Apmyp/2e5bb515cdaecf0c986072fb8372ac22 to your computer and use it in GitHub Desktop.
Save Apmyp/2e5bb515cdaecf0c986072fb8372ac22 to your computer and use it in GitHub Desktop.
Migrate sessions from DB to Redis

How to migrate Laravel sessions from Database to Redis

Declare new Redis database

config/database.php

'redis' => [
  // ...
  'sessions' => [
    'host' => env('REDIS_HOST', '127.0.0.1'),
    'password' => env('REDIS_PASSWORD', null),
    'port' => env('REDIS_PORT', 6379),
    'database' => 13,
  ],
]

Laravel command which do the migration

Don't forget to register the command in the console Kernel.

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class SessionDatabaseToRedis extends Command
{
    protected $signature = 'sessions:migrate_database_to_redis';
    protected $description = 'Переносит сессии из базы в редис, лайк э про';
    
    public function handle()
    {
        DB::table('sessions')->chunkById(1000, function($sessions) {
            foreach ($sessions as $session) {
                $sessionID = $session->id;
                $sessionData = serialize(base64_decode($session->payload));

                echo "*3\r\n$3\r\nSET\r\n$" . (strlen($sessionID) + 8) . "\r\nlaravel:" . $sessionID . "\r\n$" . strlen($sessionData) . "\r\n" . $sessionData . "\r\n";
            }
        });

        return 0;
    }
}

Run the command

The -n 13 part is about Redis database number. Check it out in the config/database file.

$ php artisan sessions:migrate_database_to_redis | redis-cli -n 13 --pipe

Change the session driver

.env

SESSION_DRIVER=redis
SESSION_CONNECTION=sessions
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379

Clear cache

$ php artisan cache:clear && php artisan config:cache

That's it

You're awesome!

About author

Channel Author
Telegram userpic Apmyp userpic
@Apmyp
Copy link
Author

Apmyp commented Jun 13, 2020

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment