当我最近使用nestjs redis时,没有官方的例子,我不知道如何正确使用它。
应用模块ts
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { typeOrmConfig } from './config/typeorm.config';
import { AuthModule } from './base/auth.module';
import { RedisModule } from 'nestjs-redis';
import { SmsService } from './common/providers/sms.service';
import { redisConfig } from './config/redis.config';
import { RedisClientService } from './common/providers/redis-client.service';
@Module({
imports: [
TypeOrmModule.forRoot(typeOrmConfig),
AuthModule,
RedisModule.register(redisConfig),
],
providers: [SmsService, RedisClientService],
})
export class AppModule {}
redis-client.service.ts
import { Injectable } from '@nestjs/common';
import { RedisService } from 'nestjs-redis';
import * as Redis from 'ioredis';
@Injectable()
export class RedisClientService {
// I want to add a private variable.
private _client
constructor(
private readonly redisService: RedisService,
) {
this.getClient().then((client) => (this._client = client));
}
async getClient(): Promise<Redis.Redis> {
const client = await this.redisService.getClient('main');
return client;
}
async setValue(key: string, value: string, expiryMode: string|any, time: string|any) : Promise<boolean>{
// use _client in this method
// this._client.set() // this is correct?
const client = await this.getClient();
const result = await client.set(key, value, expiryMode, time);
return result == 'OK';
}
}
上面的示例声明了一个变量 _client
,但我不知道如何正确使用它?
1条答案
按热度按时间uxh89sit1#
我的决定是:
创建专用变量
_client
在课堂上。在构造函数中输入初始值。
在以下方法中使用:
getValue
以及setValue
很 完美。