查看 Netsjs 文档,我可以看到一般方法是使用 CacheInterceptor 的 Controller 级缓存,
我想要实现的是服务/数据库级缓存 - 用例主要用于其他服务所需的静态数据库数据,有没有办法扩展提供的缓存模块以从服务内部使用?
最佳答案
这就是我的做法(一些钩子(Hook)):
import {CACHE_MANAGER, CacheModule, Inject, Module} from '@nestjs/common';
import {Cache} from 'cache-manager';
let cache: Cache;
@Module({
imports: [CacheModule.register({ttl: 60 * 60})]
})
export class CacheableModule {
constructor(@Inject(CACHE_MANAGER) private cacheManager: Cache) {
cache = cacheManager;
}
}
export const Cacheable = (target: any, propertyKey: string, descriptor: PropertyDescriptor) => {
const originalMethod = descriptor.value;
descriptor.value = async function (...args: any[]) {
const cacheKey = originalMethod.name + "_" + args.join('_')
const cachedData = await cache.get(cacheKey);
if (cachedData) {
originalMethod.apply(this, args).then((data: any) => {
cache.set(cacheKey, data);
})
return cachedData;
}
const result = await originalMethod.apply(this, args);
cache.set(cacheKey, result);
return result;
};
};
@Cacheable
async getProducts(projectName: string): Promise<{ [id: string]: Product }> {}
关于Nestjs 服务级缓存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59047801/