Laravel缓存应该记住我的API秘密1小时,但它没有';T
我正在尝试从外部API获取令牌。令牌持续1小时,所以我想将其放入缓存,持续时间为1小时Laravel缓存应该记住我的API秘密1小时,但它没有';T,laravel,caching,Laravel,Caching,我正在尝试从外部API获取令牌。令牌持续1小时,所以我想将其放入缓存,持续时间为1小时 $seconds = 60*60; $token = Cache::remember('nova_api_token', $seconds, function () use ($request, $credentials) { try { $response = Http::asForm() ->withHe
$seconds = 60*60;
$token = Cache::remember('nova_api_token', $seconds, function () use ($request, $credentials) {
try {
$response = Http::asForm()
->withHeaders(["Content-Type" => "application/x-www-form-urlencoded"])
->withBasicAuth($credentials->nova_id, $credentials->nova_secret)
->post(config('nova.url') . "/v1/oauth2/token", [
"grant_type" => "client_credentials"
]);
$body = json_decode($response->body());
return $body->access_token;
} catch (\Exception $e) {
return response()->json($e->getMessage(), $e->getCode());
}
});
return $token;
我可以得到我的令牌,但每次我发送post请求时,我都会得到一个不同的令牌
我所期望的是,令牌在1小时内是相同的
为什么会发生这种情况?通常是try/catch块作为一个内部函数导致问题,请尝试重构:
try {
$seconds = 60*60;
$token = Cache::remember('nova_api_token', $seconds, function () use ($request, $credentials) {
$response = Http::asForm()
->withHeaders(["Content-Type" => "application/x-www-form-urlencoded"])
->withBasicAuth($credentials->nova_id, $credentials->nova_secret)
->post(config('nova.url') . "/v1/oauth2/token", [
"grant_type" => "client_credentials"
]);
$body = json_decode($response->body());
return $body->access_token;
});
return $token;
} catch (\Exception $e) {
return response()->json($e->getMessage(), $e->getCode());
}
尝试使用rememberForever,看看它是否存储在redis中。
我建议使用now()->addHour()而不是60*60,因为函数也接受时间戳。这是什么意思:但每次发送post请求时,我都会得到不同的令牌?当您调用
Cache::get('nova_api_token')代码>多次,它是否每次都返回一个新令牌?不,我从不调用Cache::get。我调用Cache::记住,它应该调用Cache::get('nova_api_token'),如果键不存在,它将使用该键执行查询。-->是的,对不起,我不清楚,我的意思是在您执行第一个请求并生成令牌之后,当您运行Cache::get('nova_api_token')
在tinker中,它是返回null还是返回api令牌?只是为了确保值实际存储在缓存中。是的,使用Tinker,我得到null。我还检查了我的redis实例,我没有密钥“nova_api_密钥”可能是您的redis连接没有在Laravel中正确配置,如果您运行Cache::set('test',123)代码>在tinker中,您是否得到异常,或者它是否正确地将其写入缓存?看起来很奇怪,它没有在redis中写入任何内容,但没有抛出异常。我删除了try-catch,并且它没有改变任何内容。。。不工作在返回令牌之前,能否尝试转储缓存以查看是否已设置?dd(Cache::get('nova_api_token');当我在Cache::memory之前执行这个dd()时,我得到null,但当我在Cache::memory之后执行时,它返回令牌重构后是否运行了php artisan Cache:clear?我使用Cache::memberforever和dump(Cache::get('nova_api_令牌');前后。前面的一个始终为null,这意味着它不会写入缓存:(将尝试put()尝试删除缓存中的所有代码::记住()只需返回1,看看它是否已存储,如果您绝对确定redis正在工作,那么代码就有问题。似乎当我使用Tinker执行此操作时,它将记住令牌,但当我从postman调用它时,它将不会记住它…尝试更改缓存对象的名称:“nova_api_令牌”。