首页 > 解决方案 > 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 周,因此查询失败后不会重试。

标签: laravel

解决方案


推荐阅读