Nestjs 服务级缓存 [英] Nestjs Service level caching

查看:62
本文介绍了Nestjs 服务级缓存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

查看 Netsjs 文档,我可以看到一般方法是使用 CacheInterceptor 的控制器级缓存,

Looking at Netsjs documentation I can see that the general approach is controller level caching utilizing CacheInterceptor,

我希望实现的是服务/数据库级缓存 - 用例主要用于其他服务所需的静态数据库数据,有没有办法扩展提供的缓存模块以在服务内使用?

What I am looking to achieve is Service/DB level caching - use case is mainly for Static DB data that is required by other services, Is there a way to extend the supplied Cache Module to be used from within services ?

推荐答案

我也在寻找一种方法来做到这一点.

I was also looking for a way to do this.

现在,我通过在服务中注入 cacheManager 实例并直接使用它,根据一些研究使其工作.

For now I made it work based on some research by injecting the cacheManager instance in the service, and using it directly.

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;
  }
}

但我仍在寻找一种方法来创建一个包含缓存逻辑的缓存装饰器,并将使用函数参数作为缓存键

But I'm still looking for a way to create a caching decorator that would contain the cache logic, and would use the function arguments as cache key

这篇关于Nestjs 服务级缓存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆