node.js - 缓存服务方法的返回值
问题描述
我正在使用nestjs并且刚刚安装了cache-manager
模块并试图缓存来自服务调用的响应。
我在示例模块(sample.module.ts)中注册了缓存模块:
import { CacheInterceptor, CacheModule, Module } from '@nestjs/common';
import { SampleService } from './sample.service';
import { APP_INTERCEPTOR } from '@nestjs/core';
import * as redisStore from 'cache-manager-redis-store';
@Module({
imports: [
CacheModule.register({
ttl: 10,
store: redisStore,
host: 'localhost',
port: 6379,
}),
],
providers: [
SampleService,
{
provide: APP_INTERCEPTOR,
useClass: CacheInterceptor,
}
],
exports: [SampleService],
})
export class SampleModule {}
然后在我的服务中(sample.service.ts):
@Injectable()
export class SampleService {
@UseInterceptors(CacheInterceptor)
@CacheKey('findAll')
async findAll() {
// Make external API call
}
}
查看 redis 我可以看到服务方法调用没有缓存任何内容。如果我对控制器使用相同的方法,那么一切正常,我可以在我的 redis 数据库中看到缓存的条目。我认为没有办法在nestjs中缓存单个服务方法调用。
阅读documentation
似乎我只能将这种方法用于控制器、微服务和 websockets,而不能用于普通服务?
解决方案
正确,不能以与控制器相同的方式对服务使用缓存。
这是因为魔法发生在CacheInterceptor
并且Interceptors
只能在 中使用Controllers
。
但是,您可以将其cacheManager
注入您的服务并直接使用它:
export class SampleService {
constructor(@Inject(CACHE_MANAGER) protected readonly cacheManager) {}
findAll() {
const value = await this.cacheManager.get(key)
if (value) {
return value
}
const respone = // ...
this.cacheManager.set(key, response, ttl)
return response
}
推荐阅读
- python - 该模块不知道它在 Python 中的已知包
- c# - 如何使用 ASP.NET MVC 在控制器函数中将选中的复选框作为参数传递
- xslt - XSLT:将字符串的特定字符单独转换为字符串*包括*它们的十六进制值
- javascript - 更改对象数组中的键 || javascript
- android - 从片段中隐藏父活动底部导航不起作用
- javascript - 使用 Blob 将对象下载为 JSON 而不创建 DOM 元素
- c++ - 调用 setVisible(false) 在 QWidget 的构造函数中不起作用
- c - 如何为 C 中的结构正确分配内存?
- header - 如何通过 In Flow 调解器将标头参数添加到 wso2 apim 2.6.0 中的 REST API
- laravel - 如果没有数据 Laravel 如何抛出异常?