我目前正在Laravel(5.3)上製作應用程序,並要求列出所有登錄用戶。我原本打算將它們存儲在MySQL中,但被告知Redis會更適合這項工作。一旦我查看Redis文檔,我將把所有用戶存儲在一個集合中,但後來意識到您無法爲單個成員設置過期時間,因此選擇了命名空間字符串。如何列出Laravel和Redis中的所有登錄用戶?
我寫了一些代碼,我相信它運行正常,但想要改善它/解決任何可能出現的問題的建議。
因此,首先,這裏有兩個功能我LoginController.php
// Overriding the authenticated method from Illuminate\Foundation\Auth\AuthenticatesUsers
protected function authenticated(Request $request, $user)
{
$id = $user->id;
// Getting the expiration from the session config file. Converting to seconds
$expire = config('session.lifetime') * 60;
// Setting redis using id as namespace and value
Redis::SET('users:'.$id,$id);
Redis::EXPIRE('users:'.$id,$expire);
}
//Overriding the logout method from Illuminate\Foundation\Auth\AuthenticatesUsers
public function logout(Request $request)
{
// Deleting user from redis database when they log out
$id = Auth::user()->id;
Redis::DEL('users:'.$id);
$this->guard()->logout();
$request->session()->flush();
$request->session()->regenerate();
return redirect('/');
}
接下來加入我寫的中間件,以刷新Redis的到期當用戶做一些事情,刷新稱爲「RefreshRedis」他們會話。
public function handle($request, Closure $next)
{
//refreshing the expiration of users key
if(Auth::check()){
$id = Auth::user()->id;
$expire = config('session.lifetime') * 60;
Redis::EXPIRE('users:'.$id,$expire);
}
return $next($request);
}
我再註冊在$ middlewareGroups中間件只是StartSession中間件
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\App\Http\Middleware\RefreshRedis::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
'api' => [
'throttle:60,1',
'bindings',
],
];
後,爲了讓所有我以前在this線程發現功能的修改版本的用戶列表。
class Team extends AbstractWidget
{
/**
* Treat this method as a controller action.
* Return view() or other content to display.
*/
public function run()
{
//Find all logged users id's from redis
$users = $this->loggedUsers('users:*');
return view('widgets.team',compact('users'));
}
protected function loggedUsers($pattern, $cursor=null, $allResults=array())
{
// Zero means full iteration
if ($cursor==="0"){
$users = array();
foreach($allResults as $result){
$users[] = User::where('id',Redis::Get($result))->first();
}
return $users;
}
// No $cursor means init
if ($cursor===null){
$cursor = "0";
}
// The call
$result = Redis::scan($cursor, 'match', $pattern);
// Append results to array
$allResults = array_merge($allResults, $result[1]);
// Get rid of duplicated values
$allResults = array_unique($allResults);
// Recursive call until cursor is 0
return $this->loggedUsers($pattern, $result[0], $allResults);
}
}
當用戶的會話過期時,他們的登錄會自動過期。所以你沒有理由實現這個邏輯。 你可以在'config/session.php'中配置這個''lifetime'=> 120'默認值是2小時 – WebKenth
等等,我將如何得到所有當前登錄用戶的列表而沒有這個邏輯? – Dalek
並不是說你不能製作活躍用戶的列表,只是說你不需要寫實驗邏輯。您只需在登錄時添加用戶,並在會話過期時將其刪除,然後您可以隨時查詢列表以獲取活動用戶。 – WebKenth