Laravel all sessions IDs with Redis driver

2019-07-27 23:48发布

问题:

In my application I want to allow for some user, to be able to sign out all other users except him/her. I have done this functionality, well, when the Session driver was set to file, but now I'm using redis as session driver and I could not able to find any way to list up all current sessions like I have done when it was file driver.

The question is: How to list up all sessions IDs when using redis as a session driver?

The following is the code that I have used when session driver was file:

public function signoutAllUsers(Request $request,$sesId=null){
        //dd(session());
        if ($sesId == session()->getId()){
            $dir = storage_path().'/framework/sessions';
            $files = scandir($dir);
            foreach ($files as $file){
                if ($file == session()->getId() || strpos($file,'.') !== false){
                    //echo "ggg";
                    continue;
                }
                try{
                    unlink($dir.'/'.$file);
                }
                catch(\Exception $e){
                    return $e;
                }                

            }
            $request->session()->flash('status','success');
            $request->session()->flash('msg',__('All users have been signed out successfully'));
            return redirect('/method/create');

        }
        else{
            return redirect('/method/create');
        }

    }

Update

I have found a limited solution that depends on Redis facade method command:

Redis::command('keys',['*']) However, it returns output looks like:

array:4 [▼ 0 => "laravel:cav17Job1_7l46wAdE2--__" 1 => "laravel:cav17Job1_7l46wAdE2--_" 2 => "laravel:WwerTYmw2VNAfR5nKj3OOGBp2hKytSBK4MWMJ2P9" 3 => "laravel:12tyuwzoFhXPM4f6w4yRPxrYywPon4W41neq6gu" ] The above output contains both sessions ids and other cache entries, in my application I am using Redis for cache too.

The question becomes, How could I give sessions stored in redis, different key other than laravel which is the cache key?

回答1:

Keep your session and cache separate.

In the file \config\database.php

You can set many redis connections, by default there is a "default" but you can add more to it

let's say you created 'session-connection' and 'cache-connection'

now you need to make use of it

go to file 'config\session.php'

and set it to 'connection' => 'session-connection',

then go to file config\cache.php

and set it to

    'redis' => [
        'driver'     => 'redis',
        'connection' => 'cache-connection',
    ],

and now you can get your redis session records.

use Illuminate\Support\Facades\Redis;
\Log::debug( Redis::connection('session-connection')->keys('*') );