gpt4 book ai didi

javascript - Nestjs如何控制缓存?

转载 作者:行者123 更新时间:2023-11-29 23:03:26 25 4
gpt4 key购买 nike

最近看了nestjs的文档,学到了一些东西。

但我发现了一些令我困惑的事情。

Techniques/Caching ,文档向我展示了在 Controller 上使用像 @UseInterceptors(CacheInterceptor) 这样的装饰器来缓存它的响应(默认跟踪路由)。

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

在我看来,缓存存储必须提供一个 API 来按键清除缓存,以便它可以在数据更改时更新缓存(通过显式调用清除 API)。

有什么办法吗?

最佳答案

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

例子

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

关于javascript - Nestjs如何控制缓存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55156379/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com