使用Nestjs将一个值存储在Redis存储中

7

我有一个简单的nestjs应用程序,通过以下方式设置了使用Redis存储的CacheModule

import * as redisStore from 'cache-manager-redis-store';

CacheModule.register({
      store: redisStore,
      host: 'redis',
      port: 6379,
    }),

我想使用缓存来存储单个值,但我不想通过将拦截器附加到控制器方法的内置方式来实现,而是要手动控制并能够在代码中设置和检索该值。
如何操作以及是否需要使用缓存管理器?

1
如果你想在 Nest 应用中使用 Redis,最好使用已经由其他人提供的 Redis 模块。该模块具有一个服务,通过它你可以将任何你想要的内容设置和获取到 Redis 中。 nestjs-redis - fazlu
3个回答

17
你可以使用 Nest.js 的官方方式:
1. 创建你的 RedisCacheModule:
1.1. `redisCache.module.ts`:
import { Module, CacheModule } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';
import * as redisStore from 'cache-manager-redis-store';
import { RedisCacheService } from './redisCache.service';

@Module({
  imports: [
    CacheModule.registerAsync({
      imports: [ConfigModule],
      inject: [ConfigService],
      useFactory: async (configService: ConfigService) => ({
        store: redisStore,
        host: configService.get('REDIS_HOST'),
        port: configService.get('REDIS_PORT'),
        ttl: configService.get('CACHE_TTL'),
      }),
    }),
  ],
  providers: [RedisCacheService],
  exports: [RedisCacheService] // This is IMPORTANT,  you need to export RedisCacheService here so that other modules can use it
})
export class RedisCacheModule {}

1.2. redisCache.service.ts:

import { Injectable, Inject, CACHE_MANAGER } from '@nestjs/common';
import { Cache } from 'cache-manager';

@Injectable()
export class RedisCacheService {
  constructor(
    @Inject(CACHE_MANAGER) private readonly cache: Cache,
  ) {}

  async get(key) {
    await this.cache.get(key);
  }

  async set(key, value) {
    await this.cache.set(key, value);
  }
}

2. 在需要的地方注入 RedisCacheModule:

假设我们将在模块 DailyReportModule 中使用它:

2.1. dailyReport.module.ts

import { Module } from '@nestjs/common';
import { RedisCacheModule } from '../cache/redisCache.module';
import { DailyReportService } from './dailyReport.service';

@Module({
  imports: [RedisCacheModule],
  providers: [DailyReportService],
})
export class DailyReportModule {}

2.2. dailyReport.service.ts:

我们将在这里使用redisCacheService

import { Injectable, Logger } from '@nestjs/common';
import { Cron } from '@nestjs/schedule';
import { RedisCacheService } from '../cache/redisCache.service';

@Injectable()
export class DailyReportService {
  private readonly logger = new Logger(DailyReportService.name);

  constructor(
    private readonly redisCacheService: RedisCacheService, // REMEMBER TO INJECT THIS
  ) {}

  @Cron('0 1 0 * * *') // Run cron job at 00:01:00 everyday
  async handleCacheDailyReport() {
    this.logger.debug('Handle cache to Redis');
  }
}

你可以在这里查看我的示例代码。

安装后出现错误。 找不到“cache-manager-redis-store”模块的声明文件。 - har17bar
1
@har17bar,对于你来说,npm install cache-manager-redis-store 应该就可以解决问题了。 - Kekson

4

3
该项目看起来已经被放弃了,并且不兼容NestJS 8+。 - matheusr
nestjs-redis 在后台使用的是 ioredis 而不是 node-redis 模块! - Khashayar

0
如果您连接外部Redis,我建议使用“async-redis”包。
代码将是:
import * as redis from 'async-redis';
import redisConfig from '../../config/redis';

关于redisConfig:
export default {
   host: 'your Host',
   port: parseInt('Your Port Conection'),
   // Put the first value in hours
   // Time to expire a data on redis
   expire: 1 * 60 * 60,
   auth_pass: 'password',
};

所以,你运行:

var dbConnection = redis.createClient(config.db.port, config.db.host, 
{no_ready_check: true}); 

现在您可以为您的Redis数据库执行set和get等命令。

安装后出现错误。找不到“cache-manager-redis-store”模块的声明文件。 - har17bar
@har17bar 请尝试安装此软件包:https://www.npmjs.com/package/cache-manager-redis-store - Aurélio Oliveira

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接