맞춤 `@Cacheable` 데코레이터를 사용하여 Nest.js 성능 향상

Susan Sarandon
풀어 주다: 2024-09-28 06:21:02
원래의
164명이 탐색했습니다.

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

캐싱은 애플리케이션의 성능과 확장성을 향상시키는 기본 기술입니다. Nest.js에서는 내장된 캐시 관리자를 사용하여 캐싱을 원활하게 통합할 수 있습니다. 이 문서에서는 Nest.js 서비스 또는 컨트롤러에서 캐싱을 단순화하기 위해 사용자 정의 @Cacheable 데코레이터를 만드는 방법을 살펴보겠습니다.

? 사용자 정의 @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<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(Time-To-Live) 및 최대 항목 수(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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:dev.to
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
저자별 최신 기사
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!