NestJs使用ioredis配置Redis

本地安装Redis

Windows

下载地址:https://github.com/MicrosoftArchive/redis/releases,下载Zip格式并解压,打开redis-server.exe,开启redis服务

Linux

// 查看系统是否安装redis
yum info redis
 
// 如果没有安装,执行以下步骤
// 安装epel库
yum install epel-release -y
// 安装redis
yum install redis -y
 
// 操作
启动:systemctl start redis
重启:systemctl restart redis
关闭:systemctl stop redis
 
// 设置开机启动
systemctl enable redis

Mac

brew install redis
 
brew services start redis
 
redis-server /usr/local/etc/redis.conf

项目中安装redis

pnpm add ioredis
pnpm add @nestjs/microservices -D

自定义Redis服务

@@filename(redis-cache.service.ts)
import { HttpException, HttpStatus, Injectable } from '@nestjs/common'
import { Redis, type RedisKey } from 'ioredis'
 
// 自定义Redis服务
@Injectable()
export class RedisCacheService {
  constructor(private readonly redis: Redis) {}
 
  // 获取redis
  async get(key) {
    try {
      const res = await this.redis.get(key)
      return JSON.parse(res)
    } catch (e) {
      throw new HttpException(e, HttpStatus.BAD_REQUEST)
    }
  }
 
  // 设置redis
  async set(key: string, value, ttl = 10000) {
    try {
      return await this.redis.set(key, JSON.stringify(value), 'EX', ttl)
    } catch (e) {
      throw new HttpException(e, HttpStatus.BAD_REQUEST)
    }
  }

  /**
   * 删除redis
   */
  async delete(key: RedisKey[]) {
    try {
      return await this.redis.del(key)
    } catch (e) {
      throw new HttpException(e, HttpStatus.BAD_REQUEST)
    }
  }
}

初始化Redis

@@filename(redis-cache.module.ts)
import { Module } from '@nestjs/common'
import { Transport, ClientsModule } from '@nestjs/microservices'
import { Redis } from 'ioredis'
import { RedisCacheService } from './redis-cache.service'
 
@Module({
  imports: [
    // 初始化redis,redis参数建议配置到外部配置文件引入
    ClientsModule.register([
      {
        name: 'MATH_SERVICE',
        transport: Transport.REDIS,
        options: {
          host: 'redis://localhost:6379',
        },
      }
    ]),
  ],
  providers: [ RedisCacheService, Redis ],
  exports: [ RedisCacheService ]
})
 
export class RedisCacheModule {}

使用Redis服务(以UserModule为例)

user.module.ts

@@filename(user.module.ts)
import { Module } from '@nestjs/common'
import { UserService } from './user.service'
import { UserController } from './user.controller'
import { RedisCacheModule } from 'src/common/redis-catch/redis-cache.module'

/**
 * @description 用户模块
 */
@Module({
  imports: [ 
  	// 导入Redis模块
    RedisCacheModule
  ],
  controllers: [ UserController ],
  providers: [ UserService ],
  exports: [ UserService ]
})

export class UserModule {}

user.service.ts

@@filename(user.service.ts)
import { Injectable } from '@nestjs/common'
import { RedisCacheService } from 'src/common/redis-catch/redis-cache.service'

/**
 * @description 用户服务
 */
@Injectable()
export class UserService {
  constructor(
    private readonly redisCacheService: RedisCacheService,
  ) {}

  async create() {
    // 存储到redis
    this.redisCacheService.set('要存储的key值', '要存储的数据', 60 * 30)
    // 读取redis
    this.redisCacheService.get('要读取的key值')
    // 删除redis
    this.redisCacheService.delete([ '要删除的key值' ])
    return 'success'
  }
}

个人博客:https://www.linmeimei.top/ 欢迎访问


  • 6
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

林_深时见鹿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值