代码之家  ›  专栏  ›  技术社区  ›  pingze

如何控制Nestjs中的缓存?

  •  0
  • pingze  · 技术社区  · 5 年前

    我最近读了Nestjs的博士论文,从中学到了一些东西。

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

    Techniques/Caching ,医生教我使用 @UseInterceptors(CacheInterceptor) 在控制器上缓存其响应(默认按路由跟踪)。

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

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

    有办法吗?

    0 回复  |  直到 5 年前
        1
  •  1
  •   Kim Kern    5 年前

    你可以注入 cache-manager 实例 @Inject(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