Laravel:重新生成缓存

问题描述 投票:0回答:1

我正在使用缓存来存储数据库中的数据结构:

Cache::forever(static::DATA_STRUCTURE, json_encode($tree));

但是在生成之前应该清理旧的:

Artisan::call('cache:clear');

但是生成新的缓存需要一些时间,我想存储旧的缓存直到生成新的缓存。

我正在使用典型的文件缓存。有人可以提供一些提示吗?也许我们可以从盒子或一些包装中做到这一点。

此时我只看到一种解决方案:只需在其他文件夹中生成并删除带有缓存的旧文件夹,然后移动新文件夹而不是旧文件夹。

caching laravel-8 laravel-artisan
1个回答
0
投票

正如 Maksim 所说,你可以使用

Cache::put
,但你也可以设置像这样的临时值

// Step 1: Store the new cache data in a temporary cache key
Cache::put(static::TEMP_DATA_STRUCTURE, json_encode($tree), now()->addMinutes(5));

try {
    // Step 2: If generation is successful, update the main cache key with the new data
    Cache::forever(static::DATA_STRUCTURE, $tree);
} catch (\Exception $e) {
    // Handle any errors that occur during cache update
    Log::error('Error updating cache: ' . $e->getMessage());

    // Optionally, rollback the temporary cache key
    Cache::forget(static::TEMP_DATA_STRUCTURE);
}
© www.soinside.com 2019 - 2024. All rights reserved.