首页  >  文章  >  web前端  >  使用自定义“@Cacheable”装饰器增强 Nest.js 性能

使用自定义“@Cacheable”装饰器增强 Nest.js 性能

Susan Sarandon
Susan Sarandon原创
2024-09-28 06:21:02164浏览

Enhance Your Nest.js Performance with a Custom `@Cacheable` Decorator

缓存是提高应用程序性能和可扩展性的基本技术。在 Nest.js 中,可以使用内置的缓存管理器无缝集成缓存。在本文中,我们将探索如何创建自定义 @Cacheable 装饰器来简化 Nest.js 服务或控制器中的缓存。

?为什么使用自定义 @Cacheable 装饰器?

虽然 Nest.js 提供了强大的开箱即用的缓存机制,但直接在方法中应用缓存逻辑可能会使您的代码变得混乱。自定义装饰器抽象了此逻辑,使您的代码更干净且更易于维护。

?创建@Cacheable装饰器

让我们首先创建 @Cacheable 装饰器,我们将使用它来缓存方法的结果。

import { Cache } from 'cache-manager';

export function Cacheable(cacheKey: string) {
  return function (
    target: any,
    propertyName: string,
    descriptor: PropertyDescriptor,
  ) {
    const originalMethod = descriptor.value;

    descriptor.value = async function (...args: any[]) {
      const cache: Cache = this.cacheManager;

      if (!cache) {
        throw new Error(
          'Cannot use Cacheable() decorator without injecting the cache manager.',
        );
      }

      // Try to get cached data
      try {
        const cachedResult = await cache.get(cacheKey);
        if (cachedResult) {
          return cachedResult;
        }
      } catch (error) {
        console.error(`Cache get error for key: ${cacheKey}:`, error);
      }

      // Call the original method if cache miss
      const result = await originalMethod.apply(this, args);

      // Set the new result in cache
      try {
        await cache.set(cacheKey, result);
      } catch (error) {
        console.error(`Cache set error for key: ${cacheKey}:`, error);
      }

      return result;
    };

    return descriptor;
  };
}

?解释

  • 缓存检索:在执行原始方法之前,装饰器会检查结果是否已经缓存。
  • 缓存未命中处理:如果结果不在缓存中,则执行原始方法,然后缓存结果。
  • 错误处理:捕获并记录缓存检索或设置期间的任何错误,确保您的应用程序不会因缓存问题而崩溃。

?使用@Cacheable装饰器

以下是如何将 @Cacheable 装饰器应用到服务中的方法:

import { Injectable } from '@nestjs/common';
import { Cacheable } from './cacheable.decorator';

const SETTING_CACHE_KEY = 'settings';

@Injectable()
export class SettingsService {
  // Inject the cache manager
  constructor(private readonly cacheManager: Cache) {}

  /**
   * Retrieves settings from the cache if available, or loads them from the
   * repository and caches the result.
   *
   * @returns A promise that resolves to a `Settings` object.
   */
  @Cacheable(SETTING_CACHE_KEY)
  async getSettings(): Promise<Settings> {
    return await this.findAll();
  }

  // ... other methods like findAll() and buildTree()
}

?解释

  • 装饰器应用:@Cacheable 装饰器应用到具有特定缓存键的 getSettings() 方法。
  • 依赖注入:缓存管理器被注入到服务中以供装饰器使用。

?在 Nest.js 中集成缓存管理器

要在应用程序中使用缓存管理器,您需要在模块中注册它:

import { Module } from '@nestjs/common';
import { CacheModule } from '@nestjs/cache-manager';
import { SettingsService } from './settings.service';

@Module({
  imports: [
    CacheModule.register({
      isGlobal: true,
      ttl: 300, // Time to live in seconds
      max: 100, // Maximum number of items in cache
    }),
  ],
  providers: [SettingsService],
})
export class AppModule {}

?解释

  • 全局缓存:设置 isGlobal: true 使缓存管理器在整个应用程序中可用。
  • TTL 和最大项目数:配置缓存中的生存时间 (ttl) 和最大项目数 (max)。

?注入缓存管理器

确保将缓存管理器注入到使用 @Cacheable 装饰器的任何服务或控制器中:

import { Injectable } from '@nestjs/common';
import { Cache } from 'cache-manager';

@Injectable()
export class SettingsService {
  constructor(private readonly cacheManager: Cache) {}

  // ... your methods
}

?结论

通过创建自定义 @Cacheable 装饰器,您可以保持方法干净并专注于核心逻辑,将缓存问题留给装饰器。这种方法增强了代码的可读性和可维护性,使您的 Nest.js 应用程序更加高效和可扩展。

请随时在下面留下评论或问题。快乐编码! ?

以上是使用自定义“@Cacheable”装饰器增强 Nest.js 性能的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
上一篇:Good practice for Merge in Git下一篇:暂无