laravel 通过模式/通配符删除缓存键

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43048268/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 15:39:57  来源:igfitidea点击:

Remove cache keys by pattern/wildcard

laravellumen

提问by j3491

I'm building a REST API with Lumen and want to cache some of the routes with Redis. E.g. for the route /users/123/items I use:

我正在使用 Lumen 构建 REST API,并希望使用 Redis 缓存一些路由。例如,对于我使用的路线 /users/123/items:

$items = Cache::remember('users:123:items', 60, function () {
  // Get data from database and return
});

When a change is made to the user's items, I clear the cache with:

当对用户的项目进行更改时,我会使用以下命令清除缓存:

Cache::forget('users:123:items');

So far so good. However, I also need to clear the cache I've implemented for the routes /users/123 and /users/123/categories since those include an item list as well. This means I also have to run:

到现在为止还挺好。但是,我还需要清除我为路由 /users/123 和 /users/123/categories 实现的缓存,因为它们也包括项目列表。这意味着我还必须运行:

Cache::forget('users:123');
Cache::forget('users:123:categories');

In the future, there might be even more caches to clear, which is is why I'm looking for a pattern/wildcard feature such as:

将来,可能会有更多缓存需要清除,这就是为什么我要寻找模式/通配符功能的原因,例如:

Cache::forget('users:123*');

Is there any way to accommodate this behavior in Lumen/Laravel?

有没有办法在 Lumen/Laravel 中适应这种行为?

采纳答案by Alexey Mezenin

You can use cache tags.

您可以使用缓存标签

Cache tags allow you to tag related items in the cache and then flush all cached values that have been assigned a given tag. You may access a tagged cache by passing in an ordered array of tag names. For example, let's access a tagged cache and put value in the cache:

缓存标签允许您标记缓存中的相关项目,然后刷新已分配给给定标签的所有缓存值。您可以通过传入一个有序的标签名称数组来访问一个标签缓存。例如,让我们访问一个标记的缓存并将值放入缓存中:

Cache::tags(['people', 'artists'])->put('John', $john, $minutes);

You may flush all items that are assigned a tag or list of tags. For example, this statement would remove all caches tagged with either people, authors, or both. So, both Anne and John would be removed from the cache:

您可以刷新所有分配了标签或标签列表的项目。例如,此语句将删除所有标记为人员、作者或两者的缓存。因此,安妮和约翰都将从缓存中删除:

Cache::tags(['people', 'authors'])->flush();