缓存是一项实用而且简单的技术,有助于提高应用程序的性能。它充当提供高性能数据访问的临时数据存储。nest 中的缓存是以key - value 形式存储,类似于非关系型数据库Redis,当然nest 也可以加载Redis。
下面说明nest中的两种缓存方法
及将临时数据存储在内存中,达到后台高速访问的目的,方法如下:
第一步:安装依赖
$ npm install cache-manager
第二步:模块加载
import { CacheModule, Module } from '@nestjs/common';
import { AppController } from './app.controller';
@Module({
imports: [CacheModule.register()],
controllers: [AppController],
})
export class AppModule {}第三步:服务注入
import {CACHE_MANAGER} from "@nestjs/common";
import {Cache} from "cache-manager";
constructor(@Inject(CACHE_MANAGER) private cacheManager: Cache) {}第四步:操作数据
const value = await this.cacheManager.get('name'); //获取键值为name的数据
await this.cacheManager.set('key', 'value'); //存储数据,不指定ttl 默认是5秒过期时间
await this.cacheManager.set('key', 'value', 30000); // 指定ttl 过期时间为30s,过期后此数据被清除
await this.cacheManager.set('key', 'value', 0); // 设置为0 时数据永久保存
await this.cacheManager.del('key'); // 删除键值对数据
await this.cacheManager.reset(); // 清除整个缓存第一步:安装依赖
$ npm install cache-manager-redis-yet
第二步:配置模块
// app.module.ts
import {CacheModule} from "@nestjs/common";
import {redisStore} from 'cache-manager-redis-yet';
import {ConfigModule, ConfigService} from '@nestjs/config';
@Module({
imports: [
CacheModule.registerAsync({
isGlobal: true,
imports: [ConfigModule],
inject: [ConfigService],
useFactory: async (configService: ConfigService) => {
return {
store: await redisStore({
ttl: 5000, // 指定默认过期时间,单位ms
password: '12345678',
socket: {host: '127.0.0.1', port: 6379}
}),
};
}
})
],
controllers: [AppController],
})
export class AppModule {
}第三步:服务注入和 第四步:操作数据 如上 “内存中缓存” 一致
1. 字符串 string
await this.cacheManager.set('name', ’zhangsan‘, 300000); // 添加
await this.cacheManager.set('name', ’lisi‘, 300000); // 修改
await this.cacheManager.get('name'); // 获取
await this.cacheManager.del('name'); // 删除2. 列表 list
await this.cacheManager.set('name', [1, 2, 3, 4], 300000); // 添加
await this.cacheManager.set('name', [1, 2, 4], 300000); // 修改
// 获取相应元素,会返回Promise
let data: Promise<number[] | undefined> = this.cacheManager.get('name');
data.then((res) => {
if (res !== undefined) {
console.log(res[2]);
}
});
await this.cacheManager.del('name'); // 删除3. 哈希 hash
await this.cacheManager.set('name', {a: 2, b: 3, c: 4}, 300000); // 添加
await this.cacheManager.set('name', {a: 2, b: 6, c: 4}, 300000); // 修改
// 获取相应元素值,不会返回Promise
let data = await this.cacheManager.get('name');
console.log(data['b']);
// 删除其中某元素,保留其余
interface VType{
a: number;
b: number;
c: number;
}
let data:VType = await this.cacheManager.get('name');
let {b, ...rest} = data;
await this.cacheManager.set('name', rest, 300000); // {a: 2, c: 4}
await this.cacheManager.del('name'); // 删除全部www.haizhuan.tk