Nodejs Nestjs缓存管理插件cache-manager的使用

Nodejs Nestjs缓存管理插件cache-manager的使用
cache-manager 是一个通用的缓存管理库,可以与多种缓存后端(如内存、Redis等)配合使用。在 NestJS 项目中,你可以利用 cache-manager 来实现缓存功能。下面是一个简单的示例,展示如何在 NestJS 应用程序中使用 cache-manager

步骤1:安装依赖

首先,你需要安装 cache-manager 和你想要使用的缓存适配器(例如 Redis)。这里我们以 Redis 为例:

npm install cache-manager ioredis

步骤2:配置缓存模块

创建一个缓存服务文件,例如 cache.service.ts:

import { Injectable } from '@nestjs/common';
import * as cacheManager from 'cache-manager';
import * as redisStore from 'cache-manager-ioredis';

@Injectable()
export class CacheService {
  private cache: any;

  constructor() {
    this.cache = cacheManager.caching({
      store: redisStore,
      host: 'localhost', // Redis 服务器地址
      port: 6379,        // Redis 服务器端口
    });
  }

  async get(key: string): Promise<any> {
    return await this.cache.get(key);
  }

  async set(key: string, value: any, ttl?: number): Promise<void> {
    await this.cache.set(key, value, ttl);
  }
}

步骤3:注入缓存服务

在你的控制器或服务中注入 CacheService,并使用它来操作缓存。

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

@Controller('items')
export class ItemsController {
  constructor(private readonly cacheService: CacheService) {}

  @Get(':id')
  async getItem(@Param('id') id: string) {
    const cachedItem = await this.cacheService.get(id);

    if (cachedItem) {
      return cachedItem;
    }

    const item = await this.fetchItemFromDatabase(id); // 假设这是从数据库获取数据的方法
    await this.cacheService.set(id, item, 60); // 设置缓存,过期时间为60秒

    return item;
  }

  private fetchItemFromDatabase(id: string): Promise<any> {
    // 这里应该有从数据库获取数据的逻辑
    return Promise.resolve({ id, name: 'Sample Item' });
  }
}

步骤4:运行应用

确保你的 Redis 服务器正在运行,然后启动你的 NestJS 应用程序。

以上就是如何在 NestJS 中使用 cache-manager 来管理缓存的基本步骤。你可以根据实际需求调整缓存的配置和逻辑。


3 回复

当然,了解cache-manager在NestJS中的使用是个好主意!想象一下,你在烘焙蛋糕,但每次都要从头开始准备所有材料,是不是很浪费时间?cache-manager就像是个冰箱,帮你保存常用的材料,下次用时直接取出来即可。

首先,你需要安装cache-manager和相应的存储适配器,比如Redis:

npm install cache-manager ioredis

然后,在你的NestJS服务中配置它:

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

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

现在,你可以在控制器或服务中注入CacheService来使用它了:

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

@Injectable()
export class AppService {
  constructor(@Inject('CACHE_MANAGER') private cacheService: CacheService) {}

  async getData(key: string) {
    const data = await this.cacheService.get(key);
    if (!data) {
      // 数据不存在于缓存中,进行数据库查询或其他操作
      return '从数据库获取数据并设置缓存';
    }
    return data;
  }
}

这样,你就可以像使用魔法一样,快速地从缓存中获取数据啦!


当然可以。cache-manager 是一个非常流行的 Node.js 缓存管理库,而 NestJS 提供了对它的良好支持。下面我将通过一个简单的例子来展示如何在 NestJS 应用中使用 cache-manager

1. 安装依赖

首先,你需要安装 cache-manager 和对应的适配器(比如 cache-manager-ioredis 如果你想使用 Redis 作为缓存存储):

npm install cache-manager ioredis

2. 配置缓存模块

在你的 NestJS 应用中,你可以在一个模块中配置缓存服务。这里以 Redis 为例:

import { Module } from '@nestjs/common';
import { CacheModule, CacheInterceptor } from '@nestjs/cache-manager';
import { ConfigService } from '@nestjs/config';
import * as redisStore from 'cache-manager-ioredis';

@Module({
  imports: [
    CacheModule.registerAsync({
      useFactory: (configService: ConfigService) => ({
        store: redisStore,
        host: configService.get('REDIS_HOST'),
        port: configService.get<number>('REDIS_PORT'),
        ttl: 60, // 默认过期时间
      }),
      inject: [ConfigService],
    }),
  ],
  providers: [
    {
      provide: 'CACHE_MANAGER',
      useValue: CacheManager, // 这里假设 CacheManager 是你的缓存管理类
    },
  ],
  exports: ['CACHE_MANAGER'],
})
export class CacheConfigModule {}

注意:这里的 CacheManager 需要根据你的实际项目结构进行调整。如果你直接使用 cache-manager,你可以省略这一步。

3. 使用缓存

现在,你可以在任何服务或控制器中注入并使用缓存:

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

@Injectable()
export class AppService {
  constructor(
    @Inject(CACHE_MANAGER) private readonly cacheManager: Cache,
  ) {}

  async getData(key: string): Promise<string> {
    const data = await this.cacheManager.get(key);
    if (!data) {
      // 假设这是从数据库或其他地方获取数据的逻辑
      const newData = 'some data';
      await this.cacheManager.set(key, newData, { ttl: 60 });
      return newData;
    }
    return data;
  }
}

4. 启用拦截器

如果你想在全局范围内自动处理缓存,可以启用缓存拦截器:

import { Module, CacheModule } from '@nestjs/common';
import { APP_INTERCEPTOR } from '@nestjs/core';

@Module({
  imports: [
    CacheModule.register({
      isGlobal: true,
      store: redisStore,
      host: process.env.REDIS_HOST,
      port: process.env.REDIS_PORT,
    }),
  ],
  providers: [
    {
      provide: APP_INTERCEPTOR,
      useClass: CacheInterceptor,
    },
  ],
})
export class AppModule {}

这样,所有符合条件的方法调用都将被缓存管理。

cache-manager 是一个通用的缓存管理库,可以与 NestJS 结合使用以实现应用级别的缓存。首先安装 cache-manager 和相应的存储适配器,如 cache-manager-redis-store

npm install cache-manager ioredis cache-manager-redis-store

然后,在你的 NestJS 服务中注入 CacheManager

import { Cache, CacheManager } from '@nestjs/common';
import { Inject, Injectable } from '@nestjs/common';

@Injectable()
export class AppService {
  constructor(@Inject(CacheManager) private cacheManager: CacheManager) {}

  async getData(key: string) {
    let data = await this.cacheManager.get(key);
    if (!data) {
      data = await fetchDataFromSource(key); // 自定义函数从数据源获取数据
      this.cacheManager.set(key, data, { ttl: 60 }); // 缓存数据,存活时间为60秒
    }
    return data;
  }
}

这展示了如何设置和获取缓存项。

回到顶部