NestJS连接Redis数据库

1、下载依赖

npm install nestjs-redis

2、封装Redis常用方法,创建commonRedis.service.ts文件

import { Injectable } from '@nestjs/common';
import { RedisService } from 'nestjs-redis';
 
@Injectable()
export class CommonRedisService {
   private client: any;
   constructor(private redisService: RedisService) {
       this.getClient();
   }
 
   private async getClient() {
       this.client = await this.redisService.getClient();
   }
 
 
   /**
    * @Description: 封装设置redis缓存的方法
    * @param key {String} key值
    * @param value {String} key的值
    * @param seconds {Number} 过期时间
    * @return: Promise
    */
   public async set(key: string, value: any, seconds?: number): Promise {
       value = JSON.stringify(value);
       if (!this.client) {
           await this.getClient();
       }
       if (!seconds) {
           await this.client.set(key, value);
       } else {
           await this.client.set(key, value, 'EX', seconds);
       }
   }
 
 
   /**
    * @Description: 设置获取redis缓存中的值
    * @param key {String}
    */
   public async get(key: string): Promise {
       if (!this.client) {
           await this.getClient();
       }
 
       let data = await this.client.get(key);
 
       if (data) {
           return JSON.parse(data);
       } else {
           return null;
       }
   }
 
   /**
    * @Description: 根据key删除redis缓存数据
    * @param key {String}  
    * @return:
    */
   public async del(key: string): Promise {
       if (!this.client) {
           await this.getClient();
       }
 
       await this.client.del(key);
   }
 
   /**
    * @Description: 清空redis的缓存
    * @param {type} 
    * @return:
    */
   public async flushall(): Promise {
       if (!this.client) {
           await this.getClient();
       }
 
       await this.client.flushall();
   }
}
 

3、在使用Redis的模块module里面注入

import { Module } from '@nestjs/common';
import {RedisModule} from 'nestjs-redis'
import { CommonRedisService } from 'src/common/commonRedis.service';
import { redisConfig } from 'src/config/redisConfig';
import { VerificationCodeController } from './verificationCode.controller';
import { VerificationCodeService } from './verificationCode.service';

@Module({
  providers: [VerificationCodeService,CommonRedisService],
  controllers:[VerificationCodeController],
  imports:[RedisModule.register(redisConfig())]
})
export class VerificationCodeModule {}

4、在对应的Service中注入

import { Injectable } from '@nestjs/common';
import { CommonRedisService } from 'src/common/commonRedis.service';

@Injectable()
export class VerificationCodeService {
  constructor(private readonly commonRedisService : CommonRedisService){}
  async sendCode(){
    await this.commonRedisService.set('user','测试111',100)
  }

  async getCode(){ 
    return await this.commonRedisService.get('user')
  }
}

你可能感兴趣的:(NestJS连接Redis数据库)