【问题标题】:Can you configure the NestJS cache TTL per-endpoint?您可以为每个端点配置 NestJS 缓存 TTL 吗?
【发布时间】:2020-02-06 07:52:03
【问题描述】:

我目前正在使用文档中描述的 NestJS 缓存机制:https://docs.nestjs.com/techniques/caching

使用它,我可以使用以下内容自定义整个模块的缓存:

CacheModule.register({
  ttl: 5, // seconds
  max: 10, // maximum number of items in cache
});

但是,我希望将某些 端点 缓存的时间比其他端点更长。 (例如,不会像其他操作那样频繁更改的长时间运行的操作)

这里描述了类似的东西:https://github.com/nestjs/nest/issues/695,但看起来它在没有真正解决整个问题的情况下关闭了。

我在想象这样的事情:

@Cache({ ttl: 600 })
@Get()
findAll(): string[] {
  return service.longRunningOperation();
}

有什么想法吗?

【问题讨论】:

    标签: javascript node.js caching nestjs


    【解决方案1】:

    尚不支持通过装饰器控制 ttl 缓存。在 github 中有一个 feature request 以将其包含在未来的版本中。

    但是,您可以使用更详细的方法来处理它。将缓存管理器对象注入您的控制器构造函数并在每个所需路由上使用“包装”功能:

    constructor(
      @Inject(CACHE_MANAGER) private cacheManager
    ) {}
    
    @Get()
    async get(): Promise<any> {
      const customers = await this.cacheManager.wrap(
        '/customers',
        function() {
          return service.longRunningOperation()
        },
        { ttl: 600 }
      )
      return customers
    }
    

    【讨论】:

      【解决方案2】:

      您不能通过使用 cacheManager 来做到这一点。 您可以使用另一种方法,您可以使用 utils-decorators lib (npm install --save utils-decorators) 并利用 AsyncMemoize 装饰器。然后你只需要给你的控制器函数添加一个装饰器:

      import {memoizeAsync} from 'utils-decorators';
      
      class Controller {
      
      
       @Get('endpointA')
       @memoizeAsync(60 * 60 * 1000 * 12)
       endpointA() {
       }
      
       @Get('endpointB')
       @memoizeAsync(60 * 60 * 1000 * 24)
       endpointB() {
       }
      }
      

      【讨论】:

        【解决方案3】:

        您可以使用模块的通用 ttl 值注册 Cache 模块 然后在控制器中使用 '@nestjs/common' 包中的类 CacheInterceptor 和 CacheTTL 装饰器,如下所示

        @Get()
        @CacheTTL(100) 
        @UseInterceptors(CacheInterceptor)
        findAll(): string[] {
          return service.longRunningOperation();
        }
        

        CacheTTL Decorator 里面的值会覆盖缓存的默认过期时间值

        【讨论】:

          猜你喜欢
          • 2017-07-20
          • 1970-01-01
          • 1970-01-01
          • 2023-01-19
          • 2020-01-09
          • 1970-01-01
          • 2018-12-05
          • 2022-11-02
          • 1970-01-01
          相关资源
          最近更新 更多