外观
缓存模块
基于 ioredis 的高性能缓存服务,内置生命周期管理、健康检查、自动重连。
模块注册
typescript
import { CacheModule } from '@maxtan/nest-core'
@Module({
imports: [
CacheModule.forRoot(
{
host: 'localhost',
port: 6379,
password: 'your-password',
db: 0
},
true // 是否全局注册,默认 true
)
]
})
export class AppModule {}基础用法
typescript
import { Injectable } from '@nestjs/common'
import { CacheService } from '@maxtan/nest-core'
@Injectable()
export class YourService {
constructor(private readonly cacheService: CacheService) {}
async getData(key: string) {
// 获取缓存
const cached = await this.cacheService.get(key)
if (cached) return cached
// 设置缓存(TTL 秒)
const data = await this.fetchData()
await this.cacheService.set(key, JSON.stringify(data), 3600)
return data
}
}对象序列化
自动 JSON 序列化 / 反序列化:
typescript
// 设置对象
await this.cacheService.setObject(key, { name: 'John', age: 25 }, 3600)
// 获取对象(自动 JSON.parse)
const user = await this.cacheService.getObject<UserData>(key)批量操作
typescript
// 批量获取
const values = await this.cacheService.mget('key1', 'key2', 'key3')
// 批量设置
await this.cacheService.mset({ key1: 'value1', key2: 'value2' })计数器
typescript
const count = await this.cacheService.incr('counter:visits')健康检查
typescript
const isReady = await this.cacheService.isReady()
return { redis: isReady ? 'healthy' : 'unhealthy' }特性
- 自动重连:连接断开后自动重试,最多 10 次,间隔递增(最大 3 秒)
- 健康检查:定时检测连接状态
- 优雅关闭:模块销毁时自动断开连接,等待进行中的健康检查完成
- 懒连接:使用
lazyConnect,不阻塞应用启动
最佳实践
- 缓存策略:对频繁访问但不常变化的数据使用缓存,设置合理的 TTL
- 对象序列化:使用
setObject/getObject自动处理 JSON 序列化,避免手动JSON.parse - 批量操作:利用
mget/mset减少网络往返,提升性能 - 容错降级:Redis 不可用时 try/catch 降级到数据库查询
- Key 命名规范:使用
模块:实体:id格式,如user:profile:123
typescript
// 推荐的容错模式
@Injectable()
class UserService {
constructor(
private readonly cache: CacheService,
private readonly dao: UserDao
) {}
async getUser(id: string) {
try {
const cached = await this.cache.getObject<User>(`user:detail:${id}`)
if (cached) return cached
} catch {
// Redis 不可用时降级:直接走数据库
}
const user = await this.dao.findById(id)
if (user) {
this.cache.setObject(`user:detail:${id}`, user, 3600).catch(() => {})
}
return user
}
}健康检查集成
注册 CacheModule 后,HealthModule 会自动检测 Redis 连通性,无需额外配置。