Nodejs Nestjs缓存管理插件nestjs-redis的使用

Nodejs Nestjs缓存管理插件nestjs-redis的使用
nestjs-redis 是一个用于 NestJS 的 Redis 缓存管理插件。下面是如何安装和使用它的步骤:

1. 安装依赖

首先,你需要安装 nestjs-redis 和 Redis 客户端库:

npm install @nestjs-modules/redis redis

2. 配置模块

在你的 NestJS 应用中配置 Redis 模块。你可以在全局级别或特定模块中进行配置。

全局配置

app.module.ts 中配置:

import { Module } from '@nestjs/common';
import { APP_INTERCEPTOR } from '@nestjs/core';
import { RedisModule } from '@nestjs-modules/redis';

@Module({
  imports: [
    RedisModule.register({
      url: 'redis://localhost:6379', // Redis 服务器地址
    }),
  ],
  providers: [
    {
      provide: APP_INTERCEPTOR,
      useClass: YourInterceptor, // 如果需要的话,可以添加一个拦截器
    },
  ],
})
export class AppModule {}

特定模块配置

你也可以在特定模块中配置:

import { Module } from '@nestjs/common';
import { RedisModule } from '@nestjs-modules/redis';
import { CacheService } from './cache.service';

@Module({
  imports: [
    RedisModule.register({
      url: 'redis://localhost:6379',
    }),
  ],
  providers: [CacheService],
})
export class CacheModule {}

3. 使用 Redis

在你的服务中注入 RedisService 来使用 Redis:

import { Injectable } from '@nestjs/common';
import { InjectRedisClient, RedisClient } from '@nestjs-modules/redis';

@Injectable()
export class CacheService {
  constructor(@InjectRedisClient() private readonly redisClient: RedisClient) {}

  async get(key: string): Promise<string | null> {
    return this.redisClient.get(key);
  }

  async set(key: string, value: string, ttl?: number): Promise<void> {
    await this.redisClient.set(key, value, 'EX', ttl); // 设置过期时间(可选)
  }
}

4. 测试

你可以创建一个控制器来测试 Redis 缓存功能:

import { Controller, Get, Param } from '@nestjs/common';
import { CacheService } from './cache.service';

@Controller('cache')
export class CacheController {
  constructor(private readonly cacheService: CacheService) {}

  @Get(':key')
  async get(@Param('key') key: string): Promise<string | null> {
    return this.cacheService.get(key);
  }

  @Get('set/:key/:value')
  async set(@Param('key') key: string, @Param('value') value: string): Promise<void> {
    return this.cacheService.set(key, value, 60); // 设置缓存并设置过期时间为 60 秒
  }
}

这样,你就完成了 nestjs-redis 插件的基本配置和使用。你可以根据实际需求调整配置和逻辑。


3 回复

当然,了解nestjs-redis插件能让你的Node.js应用飞起来!想象一下,你的代码就像一位熟练的魔术师,而Redis就是他的魔法帽。首先,确保你已经安装了@nestjs-modules/redisioredis这两个宝贝:

npm install @nestjs-modules/redis ioredis

接下来,配置你的Redis模块,就像是给魔术师准备道具箱:

// redis.module.ts
import { Module } from '@nestjs/common';
import { RedisModule } from '@nestjs-modules/redis';

@Module({
  imports: [
    RedisModule.register({
      host: 'localhost',
      port: 6379,
    }),
  ],
})
export class RedisModule {}

现在,你可以像变魔术一样,在服务中注入RedisClient,开始施展缓存的魔法:

// app.service.ts
import { Inject, Injectable } from '@nestjs/common';
import { RedisClient } from '@nestjs-modules/redis';

@Injectable()
export class AppService {
  constructor(@Inject('REDIS_CLIENT') private client: RedisClient) {}

  async getCachedData(key: string) {
    const data = await this.client.get(key);
    return data ? JSON.parse(data) : null;
  }

  async setCachedData(key: string, value: any, ttl?: number) {
    await this.client.set(key, JSON.stringify(value), 'EX', ttl);
  }
}

这样,你就有了一个快速响应的魔法系统,再也不怕数据查询慢吞吞啦!


nestjs-redis 是一个用于 NestJS 项目的 Redis 缓存管理库。通过它,您可以轻松地将 Redis 集成到您的应用中,以实现高效的数据缓存。

安装

首先,你需要安装 nestjs-redisioredis(Redis客户端):

npm install @nestjs-modules/ioredis ioredis

配置

接下来,在你的模块文件(例如:app.module.ts)中进行配置:

import { Module } from '@nestjs/common';
import { APP_INTERCEPTOR } from '@nestjs/core';
import { RedisModule, RedisOptions } from '@nestjs-modules/ioredis';

@Module({
  imports: [
    RedisModule.register<RedisOptions>({
      host: 'localhost',
      port: 6379,
      db: 0,
      password: 'your-password', // 如果需要的话
    }),
  ],
  providers: [
    {
      provide: APP_INTERCEPTOR,
      useClass: YourCacheInterceptor, // 如果你有自定义的拦截器
    },
  ],
})
export class AppModule {}

使用

基本使用

你可以直接通过构造函数注入 Redis 实例来使用它:

import { Injectable } from '@nestjs/common';
import { InjectRedis } from '@nestjs-modules/ioredis';

@Injectable()
export class AppService {
  constructor(@InjectRedis() private readonly redis: any) {}

  async getHello(): Promise<string> {
    const value = await this.redis.get('hello');
    if (value) {
      return value;
    } else {
      const response = 'Hello World!';
      await this.redis.set('hello', response);
      return response;
    }
  }
}

自定义拦截器

如果你希望为特定的方法添加自动缓存功能,可以创建一个拦截器:

import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { InjectRedis } from '@nestjs-modules/ioredis';

@Injectable()
export class CacheInterceptor implements NestInterceptor {
  constructor(@InjectRedis() private readonly redis: any) {}

  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    const key = JSON.stringify(context.getArgs());
    return this.redis.get(key).then(async (cached) => {
      if (cached) {
        return cached;
      }
      const result = await next.handle().toPromise();
      this.redis.set(key, result);
      return result;
    });
  }
}

然后在控制器上应用这个拦截器:

import { Controller, Get } from '@nestjs/common';
import { CacheInterceptor } from './cache.interceptor';

@Controller()
export class AppController {
  @Get('data')
  @UseInterceptors(CacheInterceptor)
  getData() {
    return { message: 'Some data' };
  }
}

这样,每次请求 /data 的时候,都会先检查缓存,如果缓存存在则返回缓存值,否则执行实际逻辑并将结果保存到缓存中。

nestjs-redis 是一个用于 NestJS 应用的 Redis 缓存管理插件。首先,你需要安装它及 Redis 客户端:

npm install @nestjs-modules/redis redis

然后,在你的模块中配置并使用它:

import { Module } from '@nestjs/common';
import { RedisModule } from '@nestjs-modules/redis';
import { AppController } from './app.controller';
import { AppService } from './app.service';

@Module({
  imports: [
    RedisModule.register({
      host: 'localhost',
      port: 6379,
    }),
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

在服务中注入 RedisClient 并使用:

import { Inject, Injectable } from '@nestjs/common';
import { RedisClient } from 'redis';

@Injectable()
export class AppService {
  constructor(@Inject('REDIS_CLIENT') private client: RedisClient) {}

  async getHello(): Promise<string> {
    await this.client.set('key', 'value');
    const value = await this.client.get('key');
    return `Hello ${value}`;
  }
}

这样就完成了基本的 Redis 缓存管理。

回到顶部