Appearance
高速缓存
网站开发中缓存是常用开发技术,在Nest.js中可以使用多种缓存手段如内存缓存/Redis/Memcache等。
内存缓存
内在缓存使用 nest.js 进程对缓存进行管理,不过在进程中断时缓存数据会丢失,所以建议使用 redis或memcache管理缓存。
在 app.module.ts 中注册模型
import { CacheModule } from '@nestjs/common'
@Module({
imports: [
CacheModule.register({
isGlobal: true,
}),
...
],
然后在服务服务中使用
export class SmsService {
constructor(
@Inject(CACHE_MANAGER) private cacheService: Cache,
) {}
async cache(){
//设置缓存 ttl为多少秒后过期
await this.cacheService.set('banmashou', '斑马兽', { ttl: 600 })
//读取缓存
await this.cacheService.get('banmashou')
}
...
}
redis
下面配置 redis 缓存操作
安装
我们来在苹果系统中安装 redis,其他系统请参考 redis 文档学习使用。
使用brew来安装 redis
brew install redis
前台启动redis服务
redis-server
在后台运行 redis 服务
brew services start redis
查看 redis运行状态
brew services info redis
项目使用
首先安装扩展包
pnpm add redis
pnpm add -D @types/redis
然后在 app.module.ts 根模块中声明
@Module({
imports: [
CacheModule.register({
store: redisStore,
host: 'localhost',
port: 6379,
isGlobal: true,
}),
...
]
})
至于在服务中使用与上面的内存缓存是一样的,就不举例了。