」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 使用自訂“@Cacheable”裝飾器增強 Nest.js 效能

使用自訂“@Cacheable”裝飾器增強 Nest.js 效能

發佈於2024-11-01
瀏覽:548

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

?解釋

  • 快取檢索:在執行原始方法之前,裝飾器檢查結果是否已快取。
  • Cache Miss Handling:如果結果不在快取中,則執行原方法,然後快取結果。
  • 錯誤處理:捕獲並記錄快取檢索或設定期間的任何錯誤,確保您的應用程式不會因快取問題而崩潰。

?使用@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 {
    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 應用程式更加高效和可擴展。

請隨時在下面留下評論或問題。快樂編碼! ?

版本聲明 本文轉載於:https://dev.to/marrouchi/enhance-your-nestjs-performance-with-a-custom-cacheable-decorator-589o?1如有侵犯,請聯絡[email protected]刪除
最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3