UNPKG

@hz-9/a5-cache

Version:

Cache module for the @hz-9/a5-* series of repositories, based on cache-manager.

142 lines (109 loc) 3.32 kB
# @hz-9/a5-cache Cache module for the @hz-9/a5-* series of repositories, based on [cache-manager](https://github.com/node-cache-manager/node-cache-manager) v7. ## Features - ✅ 基于 cache-manager v7.x - ✅ 支持多层缓存 - ✅ 提供统一的缓存操作接口 - ✅ 支持同步和异步配置 - ✅ TypeScript 完整类型支持 - ✅ 全局模块支持 ## Installation ```bash pnpm add @hz-9/a5-cache cache-manager keyv ``` ## Quick Start ### 1. 基础使用 ```typescript import { Module } from '@nestjs/common' import { A5CacheModule } from '@hz-9/a5-cache' @Module({ imports: [ A5CacheModule.forRoot({ stores: [], // 使用默认内存存储 ttl: 60000, // 60 秒 isGlobal: true, // 全局模块 }), ], }) export class AppModule {} ``` ### 2. 使用缓存服务 ```typescript import { Injectable, Inject } from '@nestjs/common' import { A5_CACHE_SERVICE_TOKEN, A5Cache } from '@hz-9/a5-cache' @Injectable() export class UserService { constructor( @Inject(A5_CACHE_SERVICE_TOKEN) private readonly cache: A5Cache, ) {} async getUser(id: string) { // 使用 wrap 自动处理缓存 return this.cache.wrap( `user:${id}`, async () => { // 从数据库获取用户 return this.userRepository.findOne(id) }, { ttl: 300000 }, // 5 分钟 ) } async updateUser(id: string, data: any) { const user = await this.userRepository.update(id, data) // 删除缓存 await this.cache.del(`user:${id}`) return user } } ``` ### 3. 异步配置 ```typescript import { Module } from '@nestjs/common' import { A5CacheModule } from '@hz-9/a5-cache' import { ConfigModule, ConfigService } from '@nestjs/config' @Module({ imports: [ ConfigModule.forRoot(), A5CacheModule.forRootAsync({ useFactory: (configService: ConfigService) => ({ stores: [], ttl: configService.get('CACHE_TTL', 60000), }), inject: [ConfigService], }), ], }) export class AppModule {} ``` ## API Documentation ### A5Cache 主要缓存服务类,提供以下方法: #### `get<T>(key: string): Promise<T | undefined>` 获取缓存值。 #### `set<T>(key: string, value: T, ttl?: number): Promise<void>` 设置缓存值,可选 TTL(毫秒)。 #### `del(key: string): Promise<boolean>` 删除单个缓存。 #### `mdel(keys: string[]): Promise<boolean>` 批量删除缓存。 #### `clear(): Promise<boolean>` 清空所有缓存。 #### `wrap<T>(key: string, fn: () => T | Promise<T>, options?: A5CacheWrapOptions<T>): Promise<T>` 包装函数,自动处理缓存。如果缓存存在则返回缓存值,否则执行函数并缓存结果。 #### `getInstance(): A5CacheInstance` 获取原始 cache-manager 实例。 ## Configuration Options ### A5CacheModuleOptions ```typescript interface A5CacheModuleOptions { stores?: Keyv[] // 缓存存储数组(支持多层缓存) ttl?: number // 默认 TTL(毫秒) refreshThreshold?: number // 刷新阈值(毫秒) refreshAllStores?: boolean // 是否刷新所有存储层 nonBlocking?: boolean // 是否非阻塞模式 cacheId?: string // 缓存 ID isGlobal?: boolean // 是否全局模块(默认:true) } ``` ## License MIT