在nestjs提供cache http request by url/microservice message by key的module,cache module也是第三方套件cache manager的wrapper。
先安裝cache-manager套件,提供簡易in-memory cache功能
yarn add cache-manager
要啟用cache先import module
假設要cache get Users
修改src/user/user.module.ts
@Module({
imports: [
...
CacheModule.register(),
],
controllers: [
...controllersForUser,
],
providers: [
...servicesForUser,
],
exports: [
...servicesForUser,
]
})
export class UserModule {}
再到users.controller.ts對應的方法套用CacheInterceptor
@Controller('users')
export class UsersController {
constructor(
private usersService: UsersService,
){}
@ApiOkResponse({description:'Return Users Array'})
@MessagePattern({accountData:'users'})
@Get()
@UseInterceptors(CacheInterceptor) // 套用Cache Interceptor
userList(){
return this.usersService.getUsers();
}
...
}
如果要cache microservice TCP request的話,改用@CacheKey(),傳入@MessagePattern中的key,如account data
@ApiOkResponse({description:'Return Users Array'})
@CacheKey('accountData')
@MessagePattern({accountData:'users'})
@Get()
@UseInterceptors(CacheInterceptor)
userList(){
return this.usersService.getUsers();
}
要改用redis也相當容易,cache-manager有cache-manager-redis-store套件
yarn add cache-manager-redis-store
在Cache Module Register時傳入設定物件
import * as redisStore from 'cache-manager-redis-store';
@Module({
imports: [
...
CacheModule.register({
store: redisStore, // import from cache-manager-redis-store
host: '192.168.99.100', // redis server host ip
post: 6379, // port
ttl: 5, // 5秒有效
max: 50, // 50個items
}),
],
...
})
export class UserModule {}
當然如果沒有設定對,沒有找到redis server是會app crash的