使用 Nestjs 在 redis 存储中存储一个值



我有一个简单的nestjs应用程序,我在其中使用Redis存储设置了一个CacheModule,如下所示:

import * as redisStore from 'cache-manager-redis-store';
CacheModule.register({
store: redisStore,
host: 'redis',
port: 6379,
}),

我想用它来存储单个值,但是,我不想通过将拦截器附加到控制器方法来以内置方式执行此操作,而是我想手动控制它并能够在代码中设置和检索值。

我将如何做到这一点,我什至会为此使用缓存管理器吗?

你可以使用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');
}
}

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

基于Ahmad上面的评论,我使用了以下内容在我的nestjs应用程序中启用redis:

  1. 根据文档安装和设置nestjs-redishttps://www.npmjs.com/package/nestjs-redis。

  2. 请参阅此处的文档,了解如何在 Redis 存储中写入和读取值: https://github.com/NodeRedis/node-redis

如果你连接一个外部的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 等命令。

最新更新