安装
npm install nestjs-redis
连接
# cache.module.ts
import { Module } from '@nestjs/common';
import { RedisModule } from 'nestjs-redis'
import {CacheService} from './cache.service';
let options={
port: 6379,
host: '123.456.432.1', // 远程调试需要设置bindip 为0.0.0.0 并且设置密码
password: '123', // 非远程不需要密码
decode_responses:true,
db: 3
@Module({
imports: [
RedisModule.register(options),
//!!!!!!!外部模块需要使用必须先导出,外部模块引入
// 将 CacheService 引入改模块
providers: [CacheService],
// 再将 CacheService 暴露出去
exports: [CacheService]
export class CacheModule {}
使用
# cache.service.ts
import { Injectable } from '@nestjs/common';
import { RedisService } from 'nestjs-redis';
@Injectable()
export class CacheService {
public client;
constructor(private redisService: RedisService) {
this.getClient();
async getClient() {
this.client = await this.redisService.getClient()
* @Description: 封装设置redis缓存的方法
* @param key {String} key值
* @param value {String} key的值
* @param seconds {Number} 过期时间 秒秒秒!!!
* @return: Promise<any>
//设置值的方法
public async set(key:string, value:any, seconds?:number) {
value = JSON.stringify(value);
if(!this.client){
await this.getClient();
if (!seconds) {
await this.client.set(key, value);
} else {
await this.client.set(key, value, 'EX', seconds);
//获取值的方法
public async get(key:string) {
if(!this.client){
await this.getClient();
var data = await this.client.get(key);
if (!data) return;
return JSON.parse(data);
//获取值的方法
public async del(key:string) {
if(!this.client){
await this.getClient();
await this.client.del(key);
// 清理缓存
public async flushall(): Promise<any> {
if (!this.client) {
await this.getClient();
await this.client.flushall();
}