我有一个简单的nestjs应用程序,在其中使用CacheModule
商店设置了Redis
,如下所示:
import * as redisStore from 'cache-manager-redis-store';
CacheModule.register({
store: redisStore,
host: 'redis',
port: 6379,
}),
我想使用它来存储单个值,但是,我不想通过将拦截器附加到控制器方法上来以内置方式进行操作,而是希望手动控制它并能够设置并检索代码中的值。
我将如何去做,甚至还要使用缓存管理器?
答案 0 :(得分:3)
基于上面艾哈迈德的评论,我使用以下内容在我的nestjs应用程序中启用redis:
根据文档安装和设置nestjs-redis
https://www.npmjs.com/package/nestjs-redis。
有关如何在Redis存储中写入和读取值的信息,请参见此处的文档: https://github.com/NodeRedis/node-redis
答案 1 :(得分:3)
您可以使用Nest.js中的官方方法:
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 {}
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);
}
}
假设我们将在模块DailyReportModule
中使用它:
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 {}
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');
}
}
您可以检查我的示例代码here。
答案 2 :(得分: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之类的命令。