【问题标题】:How to control cache in Nestjs?如何控制 Nestjs 中的缓存?
【发布时间】:2019-08-04 23:39:01
【问题描述】:

最近看了nestjs的doc,从中学到了一些东西。

但我发现了一些让我感到困惑的事情。

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

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

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

有什么办法吗?

【问题讨论】:

  • 您是否正在寻找一种从后端删除缓存的方法?
  • @JanithKasun 我想知道如何通过Nestjs中设计的缓存模块从后端删除缓存

标签: javascript node.js typescript caching nestjs


【解决方案1】:

您也可以使用另一种方法,您可以使用 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.
 }
}

【讨论】:

    【解决方案2】:

    您可以使用@Inject(CACHE_MANAGER) 注入底层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'));
    }
    

    【讨论】:

    • 嗨@kim-kern。感谢您的回答。我想知道cacheManager变量(@Inject(CACHE_MANAGER) private cacheManager)的数据类型是什么
    • @SohelAhmedM 试试npm install --save-dev @types/cache-manager
    • 我添加了一个简单的最小 nestjs-redis-cache 示例 - gist.github.com/SOHELAHMED7/f7396fb7711aad9538e149e1b811b53c
    • 有没有办法通过配置中的标志(true/false)启用和禁用整个缓存功能
    • @Vallie 如果不查看更多详细信息,很难回答您的问题。什么时候设置flag?在服务器启动时静态还是动态?它是如何设置的? ...请打开一个新问题并包含一个描述您的用例的代码示例。 :-)
    猜你喜欢
    • 2011-10-01
    • 2016-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-29
    • 1970-01-01
    • 2020-09-22
    • 2012-06-06
    相关资源
    最近更新 更多