【问题标题】:How can I pass REDIS_URI for NestJS cache manager?如何为 NestJS 缓存管理器传递 REDIS_URI?
【发布时间】:2021-07-11 02:04:39
【问题描述】:

在官方文档中,这是将缓存管理器与 Redis 一起使用的正确方法:

import * as redisStore from 'cache-manager-redis-store';
import { CacheModule, Module } from '@nestjs/common';
import { AppController } from './app.controller';

@Module({
  imports: [
    CacheModule.register({
      store: redisStore,
      host: 'localhost',
      port: 6379,
    }),
  ],
  controllers: [AppController],
})
export class AppModule {}

来源:https://docs.nestjs.com/techniques/caching#different-stores

但是,我没有找到任何关于如何使用 REDIS_URI 传递 Redis 实例数据的文档。我需要将它与 Heroku 一起使用,我相信这是一个常见的用例。

【问题讨论】:

标签: heroku caching redis nestjs


【解决方案1】:

编辑:

现在它们是类型安全的:https://github.com/nestjs/nest/pull/8592


我已经探索了一些关于如何实例化 redis 客户端的问题。由于this line,我认为您传递给CacheModule.register 的选项将转发给Redis#createClient(来自redis 包)。因此,您可以像这样传递 URI:

CacheModule.register({
  store: redisStore,
  url: 'redis://localhost:6379'
})

试试这个,让我知道它是否有效。


编辑:

解释我是如何得到的:

{ store: redisStore, url: '...' }options

  1. Here in CacheModule.register 我发现您的 options 将使用 CACHE_MODULE_OPTIONS 令牌(作为 Nest 提供者
  2. 然后我搜索将使用此令牌的地方。然后我发现here 那些options 被传递给cacheManager.caching。在哪里cacheManageris the module cache-manager
  3. 查看cacheManager.caching 的代码here,您会发现您的options 现在是他们的args 参数
  4. 由于options.store(redisStore)是cache-manager-redis-store包导出的模块,所以args.store.create方法与redisStore.create中的功能相同
  5. 因此args.store.create(args)redisStore.create(options) 相同,最终将调用Redis.createClient passing this options

【讨论】:

  • 不错的收获!我能够在这里复制它,它确实按预期工作。谢谢!
猜你喜欢
  • 2023-01-19
  • 2022-10-16
  • 2020-10-26
  • 2014-04-10
  • 1970-01-01
  • 2017-12-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多