Как следует правильно использовать nestjs-redis? Любой пример nestjs-redis?

#redis #nestjs

#redis #nestjs

Вопрос:

Когда я недавно использовал nestjs-redis, официального примера не было, я не знаю, как его правильно использовать.

app.module.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:

Вот мое решение:

 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 resu<
  }
}

  
  1. создайте закрытую переменную _client в классе.
  2. в конструкторе введите начальное значение.
  3. используйте его в методах: getValue и setValue

Идеальный.