如何为 NestJS 缓存管理器传递 REDIS_URI?

How can I pass REDIS_URI for NestJS cache manager?

在官方文档中,这是将缓存管理器与 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 一起使用,我相信这是一个常见的用例。

编辑:

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


我已经探索了一些关于如何实例化 redis 客户端的信息。由于 this line I think that the options that you've passed to CacheModule.register will be forwarded to 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 that those options were passed to cacheManager.caching. Where cacheManager is the module cache-manager
  3. 查看 cacheManager.caching 的代码 here,您会发现您的 options 现在是他们的 args 参数
  4. 因为 options.store (redisStore) 是 cache-manager-redis-store package, args.store.create method is the same function as in redisStore.create
  5. 导出的模块
  6. 因此 args.store.create(args) 与执行 redisStore.create(options) 相同,最终将调用 Redis.createClient passing this options