查看Netsjs文档,我可以看到一般的方法是利用CacheInterceptor进行控制器级缓存,
我希望实现的是服务/数据库级缓存-用例主要用于其他服务所需的静态DB数据,是否有办法扩展要在服务内部使用的提供的缓存模块?>
答案 0 :(得分:0)
您可以使用此处列出的缓存存储区之一:https://github.com/BryanDonovan/node-cache-manager#store-engines
然后,您只需在缓存模块(https://docs.nestjs.com/techniques/caching#different-stores)中注册存储即可:
import * as redisStore from 'cache-manager-redis-store';
import { CacheModule, Module } from '@nestjs/common';
import { AppController } from './app.controller';
@Module({
imports: [
CacheModule.register({
store: redisStore,
host: 'localhost',
port: 6379,
}),
],
controllers: [AppController],
})
export class ApplicationModule {}
答案 1 :(得分:0)
我也在寻找一种方法来做到这一点。
现在,我通过在服务中注入 cacheManager 实例并直接使用它,根据一些研究使其工作。
import { CACHE_MANAGER, Inject, Injectable } from '@nestjs/common';
@Injectable()
export class MyService {
constructor(
@Inject(CACHE_MANAGER) protected readonly cacheManager
) {}
public async myMethod() {
const cachedData = await this.cacheManager.get(cacheKey);
if (cachedData) return cachedData;
const data = ''; // Do normal stuff here
this.cacheManager.set(cacheKey, data);
return data;
}
}
但我仍在寻找一种方法来创建一个包含缓存逻辑的缓存装饰器,并将使用函数参数作为缓存键