簡體   English   中英

如何緩存當前經過身份驗證的用戶?

[英]How do I cache the current authenticated user?

說明

在我的情況下,我在本地沒有users表,但我有一個 api 可以為我提供用戶列表。


獲取用戶()

我在app/Auth/ApiUserProvider.php為我的Auth::user()修改了我的getUsers()

protected function getUsers()
{
    $ch = curl_init();

    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_URL, env('API_HOST') . 'vse/accounts');

    $response = curl_exec($ch);
    $response = json_decode($response, true);

    curl_close($ch);

    return $response['data'];
}

問題

每次,我都在我的代碼中使用了Auth::user() 它調用我的 API .../vse/accounts它會影響我的應用程序中的很多延遲。


嘗試#1

會話

protected function getUsers()
{

    if(Session::has('user')){
        return Session::get('user');
    }else{
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_URL, env('API_HOST') . 'vse/accounts');
        $response = curl_exec($ch);
        $response = json_decode($response, true);
        curl_close($ch);
        $user = $response['data'];
        Session::put('user',$user);
        return $user;
    }

}

結果

需要多 2 秒。 :(


我該如何解決這個問題?

我應該開始使用緩存嗎? 如果是這樣,我該如何修改我必須做的事情?

我應該將它存儲在會話中嗎?

我現在願意接受任何建議。

對此的任何提示/建議將不勝感激!

你可以這樣做

protected function getUsers() {
    $minutes = 60;
    $user = Cache::remember('user', $minutes, function () {
        //your api stuff
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_URL, env('API_HOST') . 'vse/accounts');
        $response = curl_exec($ch);
        $response = json_decode($response, true);
        curl_close($ch);
        return $response['data'];
    });
         return $user;
}

這應該有效

有時你可能希望從緩存中檢索一個項目,但如果請求的項目不存在,也存儲一個默認值 -laravel docs

您將從緩存中獲取用戶,或者,如果他不存在,則從 api 中檢索用戶並將其添加到緩存中

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM