我注意到了Laravel应用程序的一个问题,我不太确定我是在做一些愚蠢的错误,还是有一个真正的问题。
因此,我使用App\Models\User\User模型上的多个标记存储和获取缓存的数据,如下所示
public function getSetting(String|Bool $key = false) : Mixed {
//Try
try {
return cache()->tags(["user_{$this->id}_cache", 'user_settings'])->remember("user_{$this->id}_settings", now()->addDays(1), function(){
return $this->settings()->pluck('value', 'key')->toArray();
});
} catch(\Exception $e){
//Logging errors here
}
}此函数只需获取所有用户设置并返回一个数组。
我使用两个缓存标记,因为我想涵盖这两种情况。
Laravel 缓存文档简单地声明传递要删除的标记(或作为数组的标记)。
因此,我的想法是,如果我想清除all user 的用户设置缓存,我应该能够运行以下操作
cache()->tags('user_settings')->flush();如果要删除特定用户的所有缓存,则应该能够运行
cache()->tags('user_1_cache')->flush();但出于某种原因,只有第二个示例(使用user_1_cache)有效吗?如果我运行第一个示例并尝试清除带有标记user_settings的所有缓存,则函数返回true,但不清除缓存?
我是做了什么愚蠢的错事,还是完全误解了缓存标记的工作方式?
版本
发布于 2022-10-11 19:33:33
我复制了你的场景这里。就像文件上说的那样。
class User extends Model
{
protected $fillable = ['id', 'name'];
public function cacheSettings()
{
return cache()->tags([$this->getUserCacheKey(), 'user_settings'])->remember("{$this->id}_settings", now()->addDay(), function () {
return $this->only('name');
});
}
public function getSettings()
{
return cache()->tags([$this->getUserCacheKey(), 'user_settings'])->get("{$this->id}_settings");
}
public function getUserCacheKey()
{
return "user_{$this->id}_cache";
}
}这些测试没有问题:
public function test_cache_flush_all_users()
{
Cache::clear();
$alice = new User(['id' => 1, 'name' => 'alice']);
$john = new User(['id' => 2, 'name' => 'john']);
$alice->cacheSettings();
$john->cacheSettings();
Cache::tags('user_settings')->flush();
// both deleted
$this->assertNull($alice->getSettings());
$this->assertNull($john->getSettings());
}
public function test_cache_flush_specific_user()
{
Cache::clear();
$alice = new User(['id' => 1, 'name' => 'alice']);
$john = new User(['id' => 2, 'name' => 'john']);
$alice->cacheSettings();
$john->cacheSettings();
Cache::tags($alice->getUserCacheKey())->flush();
// only alice deleted
$this->assertNull($alice->getSettings());
$this->assertNotNull($john->getSettings());
}没有您的实现的所有细节,也许您可以找出是什么导致了问题。
https://stackoverflow.com/questions/73940525
复制相似问题