缓存是一项伟大而简单的技术,可以帮助提高应用程序的性能。它充当临时数据存储,提供高性能的数据访问。
安装
$ npm install @nestjs/cache-manager cache-manager
$ npm install -D @types/cache-manager
内存缓存
Nest为各种缓存存储提供程序提供了统一的 API。内置的是内存中的数据存储。但是,您可以轻松地切换到更全面的解决方案,比如 Redis 。为了启用缓存,首先导入 CacheModule 并调用它的 register() 方法。
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { CacheModule } from '@nestjs/cache-manager';
@Module({
imports: [CacheModule.register()],
controllers: [AppController],
})
export class ApplicationModule {}
与缓存存储的交互
import { Cache, CACHE_MANAGER } from '@nestjs/cache-manager';
//为了和缓存管理器实例进行交互,需要使用CACHE_MANAGER标记将其注入到你的类,如下所示:
constructor(@Inject(CACHE_MANAGER) private cacheManager: Cache) {}
//Cache类是从cache-manager中导入的,而CACHE_MANAGER则是从@nestjs/common包中导入的。
//Cache实例(来自cache-manager包)上的get方法被用来从缓存中检索键值。如果该键在缓存中不存在,则返回null。
const value = await this.cacheManager.get('key');
//使用set方法将一个键值对添加到缓存中:
await this.cacheManager.set('key', 'value');
//缓存的默认过期时间是5秒。
//你可以为特定的键手动指定一个TTL(过期时间,以秒为单位),如下所示:
await this.cacheManager.set('key', 'value', { ttl: 1000 });
//如果要让缓存永不过期,请将配置的ttl属性设置为0。
await this.cacheManager.set('key', 'value', { ttl: 0 });
//使用del方法从缓存中删除一个键值对:
await this.cacheManager.del('key');
//使用reset方法清空整个缓存:
await this.cacheManager.reset();
自动缓存响应
拦截器针对每个字段解析器分别运行,因此,CacheModule(使用拦截器来缓存响应)将无法正常工作。要启用自动缓存响应,只需在想缓存数据的地方绑定CacheInterceptor。
@Controller()
@UseInterceptors(CacheInterceptor)
export class AppController {
@Get()
findAll(): string[] {
return [];
}
}
警告: 只有使用 GET 方式声明的节点会被缓存。此外,注入本机响应对象( @Res() )的 HTTP 服务器路由不能使用缓存拦截器。
全局缓存
为了减少重复代码量,可以将CacheInterceptor全局绑定到每个端点(endpoints):
import { CacheModule, Module, CacheInterceptor } from '@nestjs/common';
import { AppController } from './app.controller';
import { APP_INTERCEPTOR } from '@nestjs/core';
@Module({
imports: [CacheModule.register()],
controllers: [AppController],
providers: [
{
provide: APP_INTERCEPTOR,
useClass: CacheInterceptor,
},
],
})
export class AppModule {}
定制缓存
所有缓存的数据有其自己的过期时间(TTL)。要个性化不同值,将选项对象传递给register()方法。
CacheModule.register({
ttl: 5, //秒
max: 10, //缓存中最大和最小数量
});
不同的存储
服务在底层使用缓存管理器(cache-manager)。cache-manager包支持一个宽范围的可用存储,例如,设置Redis存储,简单地将该包和相应的选项传递给register()方法。
import * as redisStore from 'cache-manager-redis-store';
import { CacheModule, Module } from '@nestjs/common';
import { AppController } from './app.controller';
@Module({
imports: [
CacheModule.register({
store: redisStore,
host: 'localhost',
port: 6379,
}),
],
controllers: [AppController],
})
export class ApplicationModule {}