Nestjs 服务级缓存

标签 nestjs

查看 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/

    相关文章:

    NestJSX 从 CrudRequest 对象获取参数

    javascript - nestjs 中间件获取请求/响应主体

    Nestjs:如果 --no-spec 用于禁用规范文件生成,如何生成 "spec.ts"文件

    javascript - typescript 错误 : Type 'Document[]' is not assignable to custom type

    javascript - 错误 : No "exports" main defined in graphql-upload/package. json

    node.js - 其他服务中的 @Inject 服务 - Nest 无法解析依赖项

    javascript - 如何模拟我在 Nestjs/jest 中测试的同一类中的方法

    javascript - 使用 axios 对拦截器进行单元测试会抛出错误

    typescript - NestJS 在 e2e 测试中模拟 JWT 身份验证

    typescript - 使用 NestJS 和 TypeORM 为项目生成迁移文件