如何正确使用nestjs redis?有nestjs redis的例子吗?

kb5ga3dv  于 2021-06-09  发布在  Redis
关注(0)|答案(1)|浏览(790)

当我最近使用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 ,但我不知道如何正确使用它?

uxh89sit

uxh89sit1#

我的决定是:

import { Injectable } from '@nestjs/common';
import { RedisService } from 'nestjs-redis';
import * as Redis from 'ioredis';

@Injectable()
export class RedisClientService {
  private _client: Redis.Redis;

  constructor(private readonly redisService: RedisService) {
    this._client = this.redisService.getClient('main');
  }

  async getClient(): Promise<Redis.Redis> {
    const client = this.redisService.getClient('main');
    return client;
  }

  async setValue(
    key: string,
    value: string,
    expiryMode?: string | any[],
    time?: number | string,
  ): Promise<boolean> {
    const result = await this._client.set(key, value, expiryMode, time);
    return result == 'OK';
  }

  async getValue(key: string): Promise<string> {
    const result = await this._client.get(key);
    return result;
  }
}

创建专用变量 _client 在课堂上。
在构造函数中输入初始值。
在以下方法中使用: getValue 以及 setValue 很 完美。

相关问题