一、安装
yarn add redis
二、使用
1.在module中注册
import { createClient } from 'redis'
@Module({
providers:[{
provide: 'REDIS_CLIENT',// 定义一个服务提供者
// 创建 Redis 客户端实例
async useFactory() {
const client = createClient({
socket: {
host: '127.0.0.1',
port: 6379,
}
})
await client.connect()
return client;
}
}]
})
2.在 service中使用
import { Injectable, Inject } from '@nestjs/common';
import { RedisClientType } from 'redis';
@Injectable()
export class AppService {
@Inject('REDIS_CLIENT')
private redisClient: RedisClientType;
async getHello() {
// 获取所有值
const value = await this.redisClient.keys('*');
// 设置值
const setvalue = await this.redisClient.set('demo', '11111');
// 获取值
const getvalue = await this.redisClient.get('demo');
// 删除值 1代表成功 0代表没有
const delvalue = await this.redisClient.del('demo');
// 定时设置值 10s
const setTimevalue = await this.redisClient.set('demo', '11111', { EX: 10 })
return 'Hello World!';
}
}