按 pattern/wildcard 删除缓存键

Remove cache keys by pattern/wildcard

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

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

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

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

到目前为止一切顺利。但是,我还需要清除我为路由 /users/123 和 /users/123/categories 实现的缓存,因为它们也包含一个项目列表。这意味着我还必须 运行:

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

将来,可能会有更多缓存需要清除,这就是为什么我正在寻找 pattern/wildcard 功能,例如:

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

有什么方法可以在 Lumen/Laravel 中适应这种行为吗?

您可以使用 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();