Nestjs教程使用Redis实现缓存机制

在Nestjs项目中配置Redis缓存时遇到问题,按照官方文档安装了cache-managercache-manager-redis-store,但启动时报错"Unable to resolve cache manager"。我的Redis服务已正常运行,配置如下:

CacheModule.register({
  store: redisStore,
  host: 'localhost',
  port: 6379,
}),

请问:

  1. 是否需要额外安装其他依赖包?
  2. 这种配置方式在Nestjs v9中是否还适用?
  3. 有没有更推荐的Redis集成方案?看到有人用ioredis但不知如何与Nestjs缓存模块结合
  4. 能否提供完整的TypeScript配置示例?包括模块导入和异步配置的最佳实践

3 回复

在NestJS中使用Redis实现缓存机制可以显著提升应用性能。首先安装依赖:

npm install @nestjs/redis redis ioredis

然后配置app.module.ts

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

@Module({
  imports: [
    RedisModule.register({
      host: 'localhost',
      port: 6379,
    }),
  ],
  providers: [
    {
      provide: APP_INTERCEPTOR,
      useClass: CacheInterceptor, // 使用默认的缓存拦截器
    },
  ],
})
export class AppModule {}

接下来创建一个服务来操作Redis:

import { Inject, Injectable } from '@nestjs/common';
import { REDIS_CLIENT } from './constants'; // 自定义注入令牌
import { Redis } from 'ioredis';

@Injectable()
export class CacheService {
  constructor(@Inject(REDIS_CLIENT) private readonly redis: Redis) {}

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

  async get(key: string): Promise<any> {
    const data = await this.redis.get(key);
    return data ? JSON.parse(data) : null;
  }
}

最后,在控制器或服务中调用CacheService即可实现数据缓存。


在NestJS中使用Redis实现缓存机制,首先需要安装必要的依赖。运行以下命令安装Redis客户端ioredis和NestJS的缓存模块:

npm install ioredis @nestjs/cache-manager cache-manager ioredis

接下来,在模块中配置缓存服务。创建一个app.module.ts文件,添加如下代码:

import { Module } from '@nestjs/common';
import { CacheModule } from '@nestjs/cache-manager';
import * as RedisStore from 'cache-manager-ioredis';

@Module({
  imports: [
    CacheModule.register({
      store: RedisStore,
      host: 'localhost',
      port: 6379,
      ttl: 60, // 缓存存活时间(秒)
    }),
  ],
})
export class AppModule {}

在服务中注入CacheManager来操作缓存。例如:

import { Inject, Injectable } from '@nestjs/common';
import { Cache } from 'cache-manager';

@Injectable()
export class AppService {
  constructor(@Inject('CACHE_MANAGER') private cache: Cache) {}

  async getData(key: string) {
    const data = await this.cache.get(key);
    if (data) return data;
    // 如果缓存中没有数据,则从数据库或其他地方获取并存储到缓存
    const freshData = 'some data'; 
    await this.cache.set(key, freshData, { ttl: 60 });
    return freshData;
  }
}

这样就完成了基本的Redis缓存机制实现。当调用getData方法时,会先检查缓存,如果缓存中有数据则直接返回,否则从其他数据源获取数据并存入缓存。

NestJS使用Redis实现缓存机制教程

在NestJS中使用Redis作为缓存存储是一个常见的需求,下面是实现步骤:

1. 安装必要依赖

npm install cache-manager cache-manager-redis-store @types/cache-manager

2. 配置Redis缓存模块

创建一个Redis缓存模块:

// redis-cache.module.ts
import { Module, CacheModule } from '@nestjs/common';
import * as redisStore from 'cache-manager-redis-store';

@Module({
  imports: [
    CacheModule.register({
      store: redisStore,
      host: 'localhost', // Redis服务器地址
      port: 6379, // Redis端口
      ttl: 60, // 默认缓存过期时间(秒)
    }),
  ],
  exports: [CacheModule],
})
export class RedisCacheModule {}

3. 在服务中使用Redis缓存

// app.service.ts
import { Injectable, Cache } from '@nestjs/common';

@Injectable()
export class AppService {
  constructor(@Cache() private cacheManager) {}

  async getData(key: string) {
    const cachedData = await this.cacheManager.get(key);
    if (cachedData) {
      return cachedData;
    }
    
    // 从数据库或其他来源获取数据
    const data = await this.fetchFromDatabase(key);
    
    // 将数据缓存
    await this.cacheManager.set(key, data, { ttl: 300 });
    
    return data;
  }

  async invalidateCache(key: string) {
    await this.cacheManager.del(key);
  }
}

4. 在控制器中使用

// app.controller.ts
import { Controller, Get } from '@nestjs/common';
import { AppService } from './app.service';

@Controller()
export class AppController {
  constructor(private readonly appService: AppService) {}

  @Get('data/:key')
  async getData(@Param('key') key: string) {
    return this.appService.getData(key);
  }
}

高级配置选项

可以配置Redis连接池和更多选项:

CacheModule.register({
  store: redisStore,
  host: 'localhost',
  port: 6379,
  auth_pass: 'yourpassword', // 如果有密码
  db: 0, // 数据库编号
  ttl: 60,
  max: 100, // 最大连接数
});

注意事项

  1. 确保Redis服务器已启动并运行
  2. 在生产环境中使用环境变量配置Redis连接参数
  3. 考虑处理Redis连接失败的情况
  4. 根据业务需求设置合理的TTL(生存时间)

这种实现方式利用了NestJS的CacheModule,提供了简洁的API来操作Redis缓存。

回到顶部