구성 가능한 데이터 지속성을 통해 LRU 캐시 향상
인메모리 캐시 생성에 대한 이 가이드를 바탕으로 구성 가능한 데이터 지속성을 도입하여 더 나아가겠습니다. 어댑터 및 전략 패턴을 활용하여 캐싱 로직에서 스토리지 메커니즘을 분리하여 필요에 따라 데이터베이스 또는 서비스를 원활하게 통합할 수 있는 확장 가능한 시스템을 설계할 것입니다.
비전: ORM처럼 디커플링
목표는 핵심 로직을 변경하지 않고 캐시를 확장 가능하게 만드는 것입니다. ORM 시스템에서 영감을 받은 우리의 접근 방식에는 공유 API 추상화가 포함됩니다. 이를 통해 localStorage, IndexedDB 또는 원격 데이터베이스와 같은 저장소가 최소한의 코드 변경으로 상호 교환적으로 작동할 수 있습니다.
저장소 어댑터 기본 클래스
지속성 시스템에 대한 API를 정의하는 추상 클래스는 다음과 같습니다.
export abstract class StorageAdapter { abstract connect(): Promise<void>; abstract add(key: string, value: unknown): Promise<void>; abstract get(key: string): Promise<unknown | null>; abstract getAll(): Promise<Record<string, unknown>>; abstract delete(key: string): Promise<void>; abstract clear(): Promise<void>; }
모든 스토리지 솔루션은 이 기본 클래스를 확장하여 상호 작용의 일관성을 보장해야 합니다. 예를 들어, IndexedDB 구현은 다음과 같습니다.
예: IndexedDB 어댑터
이 어댑터는 StorageAdapter 인터페이스를 구현하여 IndexedDB 저장소에 캐시 데이터를 유지합니다.
import { StorageAdapter } from './storage_adapter'; /** * IndexedDBAdapter is an implementation of the StorageAdapter * interface designed to provide a persistent storage mechanism * using IndexedDB. This adapter can be reused for other cache * implementations or extended for similar use cases, ensuring * flexibility and scalability. */ export class IndexedDBAdapter extends StorageAdapter { private readonly dbName: string; private readonly storeName: string; private db: IDBDatabase | null = null; /** * Initializes the adapter with the specified database and store * names. Defaults are provided to make it easy to set up without * additional configuration. */ constructor(dbName: string = 'cacheDB', storeName: string = 'cacheStore') { super(); this.dbName = dbName; this.storeName = storeName; } /** * Connects to the IndexedDB database and initializes it if * necessary. This asynchronous method ensures that the database * and object store are available before any other operations. * It uses the `onupgradeneeded` event to handle schema creation * or updates, making it a robust solution for versioning. */ async connect(): Promise<void> { return await new Promise((resolve, reject) => { const request = indexedDB.open(this.dbName, 1); request.onupgradeneeded = (event) => { const db = (event.target as IDBOpenDBRequest).result; if (!db.objectStoreNames.contains(this.storeName)) { db.createObjectStore(this.storeName, { keyPath: 'key' }); } }; request.onsuccess = (event) => { this.db = (event.target as IDBOpenDBRequest).result; resolve(); }; request.onerror = () => reject(request.error); }); } /** * Adds or updates a key-value pair in the store. This method is * asynchronous to ensure compatibility with the non-blocking * nature of IndexedDB and to prevent UI thread blocking. Using * the `put` method ensures idempotency: the operation will * insert or replace the entry. */ async add(key: string, value: unknown): Promise<void> { await this._withTransaction('readwrite', (store) => store.put({ key, value })); } /** * Retrieves the value associated with a key. If the key does not * exist, null is returned. This method is designed to integrate * seamlessly with caching mechanisms, enabling fast lookups. */ async get(key: string): Promise<unknown | null> { return await this._withTransaction('readonly', (store) => this._promisifyRequest(store.get(key)).then((result) => result ? (result as { key: string; value: unknown }).value : null ) ); } /** * Fetches all key-value pairs from the store. Returns an object * mapping keys to their values, making it suitable for bulk * operations or syncing with in-memory caches. */ async getAll(): Promise<Record<string, unknown>> { return await this._withTransaction('readonly', (store) => this._promisifyRequest(store.getAll()).then((results) => results.reduce((acc: Record<string, unknown>, item: { key: string; value: unknown }) => { acc[item.key] = item.value; return acc; }, {}) ) ); } /** * Deletes a key-value pair by its key. This method is crucial * for managing cache size and removing expired entries. The * `readwrite` mode is used to ensure proper deletion. */ async delete(key: string): Promise<void> { await this._withTransaction('readwrite', (store) => store.delete(key)); } /** * Clears all entries from the store. This method is ideal for * scenarios where the entire cache needs to be invalidated, such * as during application updates or environment resets. */ async clear(): Promise<void> { await this._withTransaction('readwrite', (store) => store.clear()); } /** * Handles transactions in a reusable way. Ensures the database * is connected and abstracts the transaction logic. By * centralizing transaction handling, this method reduces * boilerplate code and ensures consistency across all operations. */ private async _withTransaction<T>( mode: IDBTransactionMode, callback: (store: IDBObjectStore) => IDBRequest | Promise<T> ): Promise<T> { if (!this.db) throw new Error('IndexedDB is not connected'); const transaction = this.db.transaction([this.storeName], mode); const store = transaction.objectStore(this.storeName); const result = callback(store); return result instanceof IDBRequest ? await this._promisifyRequest(result) : await result; } /** * Converts IndexedDB request events into Promises, allowing for * cleaner and more modern asynchronous handling. This is * essential for making IndexedDB operations fit seamlessly into * the Promise-based architecture of JavaScript applications. */ private async _promisifyRequest<T>(request: IDBRequest): Promise<T> { return await new Promise((resolve, reject) => { request.onsuccess = () => resolve(request.result as T); request.onerror = () => reject(request.error); }); } }
캐시에 어댑터 통합
캐시는 선택적 StorageAdapter를 허용합니다. 제공된 경우 데이터베이스 연결을 초기화하고 데이터를 메모리에 로드하며 캐시와 스토리지를 동기화된 상태로 유지합니다.
private constructor(capacity: number, storageAdapter?: StorageAdapter) { this.capacity = capacity; this.storageAdapter = storageAdapter; if (this.storageAdapter) { this.storageAdapter.connect().catch((error) => { throw new Error(error); }); this.storageAdapter.getAll().then((data) => { for (const key in data) { this.put(key, data[key] as T); } }).catch((error) => { throw new Error(error); }); } this.hash = new Map(); this.head = this.tail = undefined; this.hitCount = this.missCount = this.evictionCount = 0; }
왜 어댑터와 전략 패턴인가?
어댑터 패턴 사용:
- 특정 저장 메커니즘에서 캐시를 분리합니다.
- 새로운 스토리지 백엔드에 대한 확장성을 보장합니다.
전략 패턴과 결합:
- 지속성 레이어의 런타임 선택을 활성화합니다.
- 다양한 어댑터를 모의하여 테스트를 단순화합니다.
주요 설계 사례
- 추상 API: 스토리지 세부정보에 관계없이 캐시 로직을 유지합니다.
- 싱글턴 캐시: 공유 상태 일관성을 보장합니다.
- 비동기 초기화: 설정 중 작업 차단을 방지합니다.
- 지연 로딩: 스토리지 어댑터가 제공되는 경우에만 지속형 데이터를 로드합니다.
다음 단계
이 디자인은 견고하지만 개선의 여지가 있습니다.
- 더 나은 성능을 위해 동기화 로직을 최적화하세요.
- Redis 또는 SQLite와 같은 추가 어댑터를 사용해 실험해 보세요.
사용해 보세요! ?
캐시가 실제로 작동하는지 테스트하고 싶다면 npm 패키지(adev-lru)로 사용할 수 있습니다. GitHub: adev-lru 저장소에서 전체 소스 코드를 탐색할 수도 있습니다. 더 나은 앱을 만들기 위한 추천, 건설적인 피드백 또는 기여를 환영합니다! ?
즐거운 코딩하세요! ?
위 내용은 구성 가능한 데이터 지속성을 통해 LRU 캐시 향상의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제











프론트 엔드 개발시 프론트 엔드 열지대 티켓 인쇄를위한 자주 묻는 질문과 솔루션, 티켓 인쇄는 일반적인 요구 사항입니다. 그러나 많은 개발자들이 구현하고 있습니다 ...

JavaScript는 현대 웹 개발의 초석이며 주요 기능에는 이벤트 중심 프로그래밍, 동적 컨텐츠 생성 및 비동기 프로그래밍이 포함됩니다. 1) 이벤트 중심 프로그래밍을 사용하면 사용자 작업에 따라 웹 페이지가 동적으로 변경 될 수 있습니다. 2) 동적 컨텐츠 생성을 사용하면 조건에 따라 페이지 컨텐츠를 조정할 수 있습니다. 3) 비동기 프로그래밍은 사용자 인터페이스가 차단되지 않도록합니다. JavaScript는 웹 상호 작용, 단일 페이지 응용 프로그램 및 서버 측 개발에 널리 사용되며 사용자 경험 및 크로스 플랫폼 개발의 유연성을 크게 향상시킵니다.

기술 및 산업 요구에 따라 Python 및 JavaScript 개발자에 대한 절대 급여는 없습니다. 1. 파이썬은 데이터 과학 및 기계 학습에서 더 많은 비용을 지불 할 수 있습니다. 2. JavaScript는 프론트 엔드 및 풀 스택 개발에 큰 수요가 있으며 급여도 상당합니다. 3. 영향 요인에는 경험, 지리적 위치, 회사 규모 및 특정 기술이 포함됩니다.

동일한 ID로 배열 요소를 JavaScript의 하나의 객체로 병합하는 방법은 무엇입니까? 데이터를 처리 할 때 종종 동일한 ID를 가질 필요가 있습니다 ...

JavaScript를 배우는 것은 어렵지 않지만 어려운 일입니다. 1) 변수, 데이터 유형, 기능 등과 같은 기본 개념을 이해합니다. 2) 마스터 비동기 프로그래밍 및 이벤트 루프를 통해이를 구현하십시오. 3) DOM 운영을 사용하고 비동기 요청을 처리합니다. 4) 일반적인 실수를 피하고 디버깅 기술을 사용하십시오. 5) 성능을 최적화하고 모범 사례를 따르십시오.

이 기사에서 시차 스크롤 및 요소 애니메이션 효과 실현에 대한 토론은 Shiseido 공식 웹 사이트 (https://www.shiseido.co.jp/sb/wonderland/)와 유사하게 달성하는 방법을 살펴볼 것입니다.

JavaScript의 최신 트렌드에는 Typescript의 Rise, 현대 프레임 워크 및 라이브러리의 인기 및 WebAssembly의 적용이 포함됩니다. 향후 전망은보다 강력한 유형 시스템, 서버 측 JavaScript 개발, 인공 지능 및 기계 학습의 확장, IoT 및 Edge 컴퓨팅의 잠재력을 포함합니다.

Console.log 출력의 차이의 근본 원인에 대한 심층적 인 논의. 이 기사에서는 Console.log 함수의 출력 결과의 차이점을 코드에서 분석하고 그에 따른 이유를 설명합니다. � ...
