前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >nestjs连接redis

nestjs连接redis

作者头像
程序员不务正业
发布2021-12-16 09:43:21
2K0
发布2021-12-16 09:43:21
举报

安装

代码语言:javascript
复制
npm install nestjs-redis

连接

代码语言:javascript
复制
# cache.module.ts

import { Module } from '@nestjs/common';
import { RedisModule } from 'nestjs-redis'
import {CacheService} from './cache.service';
let options={
          port: 6379,
          host: '123.456.432.1', // 远程调试需要设置bindip 为0.0.0.0 并且设置密码
          password: '123',  // 非远程不需要密码
          decode_responses:true,
          db: 3
  }
@Module({
      imports: [
          RedisModule.register(options),
      ],

      //!!!!!!!外部模块需要使用必须先导出,外部模块引入
      // 将 CacheService 引入改模块
      providers: [CacheService],
      // 再将 CacheService 暴露出去
      exports: [CacheService]

  })
export class CacheModule {}

使用

代码语言:javascript
复制
# cache.service.ts
import { Injectable } from '@nestjs/common';
import { RedisService } from 'nestjs-redis';

@Injectable()
export class CacheService {
  public client;
    constructor(private redisService: RedisService) {
        this.getClient();
    }
    async getClient() {
        this.client = await this.redisService.getClient()
    }

/**
    * @Description: 封装设置redis缓存的方法
    * @param key {String} key值
    * @param value {String} key的值
    * @param seconds {Number} 过期时间 秒秒秒!!!
    * @return: Promise<any>
    */
    //设置值的方法
    public async set(key:string, value:any, seconds?:number) {
        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);
        }
    }

    //获取值的方法
    public async get(key:string) {
        if(!this.client){
            await this.getClient();
        }
        var data = await this.client.get(key);           
        if (!data) return;
        return JSON.parse(data);       
    }

    //获取值的方法
    public async del(key:string) {
        if(!this.client){
            await this.getClient();
        }
        await this.client.del(key);           
    }
    // 清理缓存
    public async flushall(): Promise<any> {
       if (!this.client) {
           await this.getClient();
       }
 
       await this.client.flushall();
   }
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2021/11/29 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 安装
  • 连接
  • 使用
相关产品与服务
远程调试
远程调试(Remote Debugging,RD)在云端为用户提供上千台真实手机/定制机/模拟器设备,快速实现随时随地测试。运用云测技术对测试方式、操作体验进行了优化,具备多样性的测试能力,包括随时截图和记录调试日志,稳定的支持自动化测试, 设备灵活调度,用例高效执行, 快速定位产品功能和兼容性问题。云手机帮助应用、移动游戏快速发现和解决问题,节省百万硬件费用,加速敏捷研发流程。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档