如何在Nestjs中控制缓存?

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

我最近阅读了nestjs的文档,并从中学到了一些东西。

但是我发现了让我困惑的事情。

Techniques/Caching中,文档显示我在控制器上使用像@UseInterceptors(CacheInterceptor)这样的装饰器来缓存其响应(默认按路径跟踪)。

我写了一个测试用例,发现它很有用。但我没有找到任何解释来说明如何清理缓存。这意味着我必须等待缓存过期。

在我看来,缓存存储必须提供一个API来按键清除缓存,这样它就可以在数据发生变化时更新缓存(通过显式调用一个明确的API)。

有没有办法做到这一点?

javascript node.js typescript caching nestjs
1个回答
1
投票

你可以用cache-manager注入底层的@Inject(CACHE_MANAGER)实例。在cache-manager实例上,您可以调用方法del(key, cb)来清除指定键的缓存,请参阅docs

Example

counter = 0;
constructor(@Inject(CACHE_MANAGER) private cacheManager) {}

// The first call increments to one, the preceding calls will be answered by the cache
// without incrementing the counter. Only after you clear the cache by calling /reset
// the counter will be incremented once again.
@Get()
@UseInterceptors(CacheInterceptor)
incrementCounter() {
  this.counter++;
  return this.counter;
}

// Call this endpoint to reset the cache for the route '/'
@Get('reset')
resetCache() {
  const routeToClear = '/';
  this.cacheManager.del(routeToClear, () => console.log('clear done'));
}

Edit nest-clear-cache

© www.soinside.com 2019 - 2024. All rights reserved.