描述
在我的情况下,我在本地没有users
表,但我有一个api,可以为我提供用户列表。
getUsers()
我在app/Auth/ApiUserProvider.php
中将getUsers()
修改为Auth::user()
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文档
您将从缓存中获取用户,或者,如果用户不存在,则从api中检索用户并将其添加到缓存