* 需要安装的包版本
@chenjm/nestjs-redis
* 新增module
import { Module } from "@nestjs/common";
import redisconfig from "../constant/redis";
import { RedisModule } from "@chenjm/nestjs-redis";
import { RedisService } from "./redis.service";
console.log("==================your redis config is=====================")
console.log(redisconfig)
@Module({
imports: [
RedisModule.forRoot({
closeClient: true,
readyLog: true,
config: {
url: `redis://redis:${redisconfig.pass}@${redisconfig.host}:${redisconfig.port}/${redisconfig.db}`,
}
})
],
providers: [RedisService],
exports: [RedisService]
})
export class Redismodel { }
在以上代码中,如果redis设置了对于的名称,则需要将//后的redis替换为自己的redis名称。
由于很多文档都年旧失修,但是对应的包版本又更新了很多版本,所以必须得看源码才能知道正确的使用方法,这一点也是非常重要的!
* 新增一个service方法
import { Injectable } from "@nestjs/common";
import { RedisService as redis } from '@chenjm/nestjs-redis';
@Injectable()
export class RedisService {
client: any
constructor(Redisservice: redis) {
this.client = Redisservice.getClient()
}
async get(key: any) {
return await this.client.get(key)
}
}
你可以在此方法中实现redis原生的其他方法(set reset),当前demo中只展示了get。
* 将Redismodel import 到其他module中使用
import { Redismodel } from '@lib/common/db/redis.module';
import { PassportModule } from '@nestjs/passport';
@Module({
imports: [
PassportModule,
Redismodel
]
})
export class AuthModule { }
比如当前demo中的我想在auth中使用redis,所以首先引入。然后在auth模块的对应service去使用。
import { RedisService } from '@lib/common/db/redis.service';
export class Auth {
constructor(private redisservice: RedisService) {
}
async testgetdata(){
return await this.redisservice.get('testkey')
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。