网上很多nestjs引入redis方法都比较笨拙,有的可能会建立多次连接,有的方法已经不适用,甚至连chatgpt给出的方法也是不好用的,今天给大家带来一个我实操的优雅封装引入方法,快去享用吧!
1、安装ioredis
npm install ioredis
2、创建redis module,并引用
nest g module redis
// redis.module.ts
import { Module, Global } from '@nestjs/common';
import { Redis } from 'ioredis';
@Global()
@Module({
providers: [
{
provide: 'REDIS',
useValue: new Redis(
host: 'your-redis-host', // 例如, '127.0.0.1'
port: 6379, // 默认为 6379
password: 'your-password', // 如果你有密码
// 你还可以设置其他选项,如 db, tls 等
),
},
],
exports: ['REDIS'],
})
export class RedisModule {}
app.module.ts引入redis.module.ts
import { RedisModule } from './redis/redis.module';
@Module({
imports: [
RedisModule
]
})
3、创建service
nest g service redis
// redis.service.ts
import { Injectable, Inject } from '@nestjs/common';
import { Redis } from 'ioredis';
@Injectable()
export class RedisService {
constructor(@Inject('REDIS') private readonly client: Redis) {}
// 查询
async get(key: string): Promise<string | null> {
return this.client.get(key);
}
// 插入 expiration为过期时间,可选
async set(key: string, value: any, expiration?: number): Promise<void> {
if (expiration) {
await this.client.set(key, value, 'EX', expiration);
} else {
await this.client.set(key, value);
}
}
// ... 其他方法
}
4、引入redis.service.ts
在需要使用的module中引入service,注意,需要在providers中引入
// xxx.modules.ts
import { RedisService } from 'src/redis/redis.service';
@Module({
providers: [RedisService]
})
在需要使用的service中引入
// xxx.service.ts
import { RedisService } from 'src/redis/redis.service';
export class XxxService {
constructor(
private readonly redisService: RedisService
){}
async testFunc(){
// 插入
await this.redisService.set(key, value);
// 查询
await this.redisService.get(key);
// 插入带过期时间,单位秒
await this.redisService.set(key, value, 60);
}
}
总结:
Redis引入成功啦!! 又为我的网站vlink.cc提升了性能!!!
follow我,技术看个乐、还得学独立开发者变现