nestjs使用redis

redis安装

1、windows安装,下载目录:Releases · microsoftarchive/redis · GitHub,解压,打开redis-server.exe,开启redis服务

2、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

3、mac安装

brew install redis

brew services start redis

redis-server /usr/local/etc/redis.conf

使用redis

安装依赖 @nestjs/microservices 和 ioredis
npm i @nestjs/microservices ioredis -S
新建 redis-cache.module.ts

推荐使用命令: nest g mo redis-cache

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-cache.service.ts

推荐使用命令: nest g s redis-cache

import { Injectable } from '@nestjs/common';
import { Redis } from 'ioredis';

@Injectable()
export class RedisCacheService {
  constructor(private readonly redis: Redis) {}

  // 获取redis
  async get(key) {
    const res = await this.redis.get(key);
    return JSON.parse(res);
  }

  // 设置redis
  async set(key, value) {
    return await this.redis.set(key, JSON.stringify(value));
  }
}
在需要使用的场景,引入以上两个文件即可

app.module.ts

...
import { RedisCacheModule } from './redis-cache/redis-cache.module';

@Module({
  imports: [
    RedisCacheModule,
  ],
  ...
})
export class AppModule {}

app.service.ts

import { Injectable } from '@nestjs/common';
import { RedisCacheService } from './redis-cache/redis-cache.service';

@Injectable()
export class AppService {
  constructor(private readonly redisCacheService: RedisCacheService) {}

  getCache(param):any {
    return this.redisCacheService.get(param.key);
  }

  setCache(param):any {
    return this.redisCacheService.set(param.key, param.value);
  }
}
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值