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
npm i @nestjs/microservices ioredis -S
推荐使用命令:?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 {}
推荐使用命令:?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);
}
}