@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
Markdown
Cache module for the @hz-9/a5-* series of repositories, based on [cache-manager](https://github.com/node-cache-manager/node-cache-manager) v7.
- ✅ 基于 cache-manager v7.x
- ✅ 支持多层缓存
- ✅ 提供统一的缓存操作接口
- ✅ 支持同步和异步配置
- ✅ TypeScript 完整类型支持
- ✅ 全局模块支持
```bash
pnpm add @hz-9/a5-cache cache-manager keyv
```
```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 {}
```
```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
}
}
```
```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 {}
```
主要缓存服务类,提供以下方法:
获取缓存值。
设置缓存值,可选 TTL(毫秒)。
删除单个缓存。
批量删除缓存。
清空所有缓存。
包装函数,自动处理缓存。如果缓存存在则返回缓存值,否则执行函数并缓存结果。
获取原始 cache-manager 实例。
```typescript
interface A5CacheModuleOptions {
stores?: Keyv[] // 缓存存储数组(支持多层缓存)
ttl?: number // 默认 TTL(毫秒)
refreshThreshold?: number // 刷新阈值(毫秒)
refreshAllStores?: boolean // 是否刷新所有存储层
nonBlocking?: boolean // 是否非阻塞模式
cacheId?: string // 缓存 ID
isGlobal?: boolean // 是否全局模块(默认:true)
}
```
MIT