laravel - Laravel 8 - 有条件地记住缓存中的值
问题描述
我正在为我的应用程序使用 API。这个 API 不能 100% 工作,所以我想缓存查询以减少失败结果的数量。为此,我想使用该Cache::remember()
方法。
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Str;
$query = ; // the query to be made in the external api
$value = Cache::remember('query-'.Str::slug($query), now()->addWeeks(1), function () use ($query) {
$baseUrl = ; // the external api's base url
$response = Http::withHeaders([/* some headers */])->get($baseUrl.$query);
return ($response->status() !== Response::HTTP_OK) ? false : $response->body();
});
但是,这将false
在缓存中保存 1 周,而不是在查询失败时不保存任何内容。
我的第二种方法是将所有内容放在一个 try-catch 块中,并在闭包内抛出一个异常。有没有更好的办法?
如果查询失败,我不想Cache::remember()
将任何内容放入缓存中,($response->status() !== Response::HTTP_OK)
因此下次运行代码时,将重试查询。
使用原样的代码,false
将在缓存中保留 1 周,因此查询失败后不会重试。
解决方案
推荐阅读
- android - Webbit 服务器在 Android 应用程序中无法正常工作
- firebase - Firebase A/B 测试 - 激活事件中缺少 first_open 事件
- android - 华为快应用configAuth失败1002
- swiftui - 如何遍历 SwiftUI 结构中的键?
- powershell - Powershell convertto-json 改变键值
- php - PHP:如何捕获致命错误:无法声明类 [myclassname],因为该名称已在使用中
- python - 在pyspark中转换为json时数据类型不匹配
- angularjs - DowngradeModule 和 downgradeInjectable 导致 Angular/AngularJS 混合应用程序中每个模块的单例服务,而不是全局单例
- php - 部署别人的Laravel项目(mysql连接问题)
- sql - 插入中的子查询