pin*_*gze 6 javascript caching node.js typescript nestjs
我最近阅读了 nestjs 的文档,并从中学到了一些东西。
但我发现了让我困惑的事情。
在Techniques/Caching 中,文档向我展示了使用像@UseInterceptors(CacheInterceptor)控制器一样的装饰器来缓存其响应(默认按路由跟踪)。
我写了一个测试用例,发现它很有用。但是我没有找到任何解释来说明如何清理缓存。这意味着我必须等待缓存过期。
在我看来,缓存存储必须提供一个 API 来通过键清除缓存,以便在数据发生变化时更新缓存(通过显式调用清除 API)。
有没有办法做到这一点?
您可以cache-manager使用@Inject(CACHE_MANAGER). 在cache-manager实例上,您可以调用该方法del(key, cb)来清除指定键的缓存,请参阅文档。
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'));
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13711 次 |
| 最近记录: |