[英]How to control cache in Nestjs?
我最近閱讀了 nestjs 的文檔,並從中學到了一些東西。
但我發現了讓我困惑的事情。
在Techniques/Caching 中,文檔向我展示了在控制器上使用像@UseInterceptors(CacheInterceptor)
這樣的裝飾器來緩存其響應(默認按路由跟蹤)。
我寫了一個測試用例,發現它很有用。 但是我沒有找到任何解釋來說明如何清理緩存。 這意味着我必須等待緩存過期。
在我看來,緩存存儲必須提供一個 API 來通過鍵清除緩存,以便在數據發生變化時更新緩存(通過顯式調用清除 API)。
有沒有辦法做到這一點?
您可以使用@Inject(CACHE_MANAGER)
注入底層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'));
}
您還可以使用另一種方法,您可以使用utils-decorators lib( npm install --save utils-decorators
)並利用 AsyncMemoize 裝飾器。 然后你只需要為你的控制器函數添加一個裝飾器:
import {memoizeAsync} from 'utils-decorators';
const cache = new Map();
class Controller {
@Get()
@memoizeAsync({cache: cache})
incrementCounter() {
this.counter++;
return this.counter;
}
@Get('reset')
resetCache() {
// do whatever you want with the cache map.
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.