ioredis 上に構築された多用途で使いやすいキャッシュ マネージャーを使用して、Node.js アプリのパフォーマンスを向上させます。キャッシュを簡素化し、効率を最適化し、運用を合理化します。
私は、使いやすさとパフォーマンスに重点を置き、自分のニーズに合わせて ioredis 上に構築されたクラスを開発しました。 TypeScript のサポートが含まれており、簡単な使用法と効率的な操作を目指しています。動的データベースの使用やより詳細なエラー処理の可能性により、さらに改善および最適化することができます。これを皆さんと共有したいと思います。改善のためのフィードバックや提案をいただければ幸いです。
import Redis, { type RedisOptions } from 'ioredis'; interface CacheConfig { defaultTTL?: number; } export class cacheManager { private static instance: cacheManager; private static redisClient: Redis; private currentKey: string | null; private defaultTTL: number; private static readonly DEFAULT_TTL = 3600; private constructor(config?: CacheConfig) { const redisConfig: RedisOptions = { db: 2, retryStrategy: (times: number) => { const delay = Math.min(times * 50, 2000); return delay; }, lazyConnect: true, maxRetriesPerRequest: 3, enableReadyCheck: true, autoResubscribe: true, autoResendUnfulfilledCommands: true, reconnectOnError: (err: Error) => { const targetError = 'READONLY'; return err.message.includes(targetError); }, }; if (!cacheManager.redisClient) { cacheManager.redisClient = new Redis(redisConfig); cacheManager.redisClient.on('error', (error: Error) => { console.error('Redis Client Error:', error); }); cacheManager.redisClient.on('connect', () => { console.debug('Redis Client Connected'); }); cacheManager.redisClient.on('ready', () => { console.debug('Redis Client Ready'); }); } this.currentKey = null; this.defaultTTL = config?.defaultTTL ?? cacheManager.DEFAULT_TTL; } public static getInstance(config?: CacheConfig): cacheManager { if (!cacheManager.instance) { cacheManager.instance = new cacheManager(config); } return cacheManager.instance; } public key(key: string): cacheManager { this.validateKey(key); this.currentKey = key; return this; } private validateKey(key: string): void { if (key.length > 100) throw new Error('Key too long'); if (!/^[\w:-]+$/.test(key)) throw new Error('Invalid key format'); } public async getValue<t>(): Promise<t null> { try { if (!this.currentKey) { throw new Error('Key is required'); } const value = await cacheManager.redisClient.get(this.currentKey); return value ? JSON.parse(value) : null; } catch (error) { console.error('getValue Error:', error); return null; } } public async getMultiple<t>(keys: string[]): Promise<record t null>> { try { const pipeline = cacheManager.redisClient.pipeline(); for (const key of keys) { pipeline.get(key); } type PipelineResult = [Error | null, string | null][] | null; const results = (await pipeline.exec()) as PipelineResult; const output: Record<string t null> = {}; if (!results) { return output; } keys.forEach((key, index) => { const result = results[index]; if (result) { const [err, value] = result; if (!err && value) { try { output[key] = JSON.parse(value); } catch { output[key] = null; } } else { output[key] = null; } } else { output[key] = null; } }); return output; } catch (error) { console.error('getMultiple Error:', error); return {}; } } public async setValue<t>(value: T, ttl: number = this.defaultTTL): Promise<boolean> { try { if (!this.currentKey) { throw new Error('Key is required'); } const stringValue = JSON.stringify(value); if (ttl) { await cacheManager.redisClient.setex(this.currentKey, ttl, stringValue); } else { await cacheManager.redisClient.set(this.currentKey, stringValue); } return true; } catch (error) { console.error('setValue Error:', error); return false; } } public async setBulkValue<t>(keyValuePairs: Record<string t>, ttl: number = this.defaultTTL, batchSize = 1000): Promise<boolean> { try { const entries = Object.entries(keyValuePairs); for (let i = 0; i (fallbackFn: () => Promise<t>, ttl: number = this.defaultTTL): Promise<t null> { try { if (!this.currentKey) { throw new Error('Key is required'); } const cachedValue = await this.getValue<t>(); if (cachedValue !== null) { return cachedValue; } const value = await fallbackFn(); await this.setValue(value, ttl); return value; } catch (error) { console.error('getOrSetValue Error:', error); return null; } } public async delete(): Promise<boolean> { try { if (!this.currentKey) { throw new Error('Key is required'); } await cacheManager.redisClient.del(this.currentKey); return true; } catch (error) { console.error('delete Error:', error); return false; } } public async exists(): Promise<boolean> { try { if (!this.currentKey) { throw new Error('Key is required'); } return (await cacheManager.redisClient.exists(this.currentKey)) === 1; } catch (error) { console.error('exists Error:', error); return false; } } public async getTTL(): Promise<number> { try { if (!this.currentKey) { throw new Error('Key is required'); } return await cacheManager.redisClient.ttl(this.currentKey); } catch (error) { console.error('getTTL Error:', error); return -1; } } public static async disconnect(): Promise<void> { if (cacheManager.redisClient) { await cacheManager.redisClient.quit(); } } } </void></number></boolean></boolean></t></t></t></boolean></string></t></boolean></t></string></record></t></t></t>
以上がTypeScript と ioredis を使用して Node.js で高性能キャッシュ マネージャーを構築するの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

JavaScriptエンジンが内部的にどのように機能するかを理解することは、開発者にとってより効率的なコードの作成とパフォーマンスのボトルネックと最適化戦略の理解に役立つためです。 1)エンジンのワークフローには、3つの段階が含まれます。解析、コンパイル、実行。 2)実行プロセス中、エンジンはインラインキャッシュや非表示クラスなどの動的最適化を実行します。 3)ベストプラクティスには、グローバル変数の避け、ループの最適化、constとletsの使用、閉鎖の過度の使用の回避が含まれます。

Pythonは、スムーズな学習曲線と簡潔な構文を備えた初心者により適しています。 JavaScriptは、急な学習曲線と柔軟な構文を備えたフロントエンド開発に適しています。 1。Python構文は直感的で、データサイエンスやバックエンド開発に適しています。 2。JavaScriptは柔軟で、フロントエンドおよびサーバー側のプログラミングで広く使用されています。

PythonとJavaScriptには、コミュニティ、ライブラリ、リソースの観点から、独自の利点と短所があります。 1)Pythonコミュニティはフレンドリーで初心者に適していますが、フロントエンドの開発リソースはJavaScriptほど豊富ではありません。 2)Pythonはデータサイエンスおよび機械学習ライブラリで強力ですが、JavaScriptはフロントエンド開発ライブラリとフレームワークで優れています。 3)どちらも豊富な学習リソースを持っていますが、Pythonは公式文書から始めるのに適していますが、JavaScriptはMDNWebDocsにより優れています。選択は、プロジェクトのニーズと個人的な関心に基づいている必要があります。

C/CからJavaScriptへのシフトには、動的なタイピング、ゴミ収集、非同期プログラミングへの適応が必要です。 1)C/Cは、手動メモリ管理を必要とする静的に型付けられた言語であり、JavaScriptは動的に型付けされ、ごみ収集が自動的に処理されます。 2)C/Cはマシンコードにコンパイルする必要がありますが、JavaScriptは解釈言語です。 3)JavaScriptは、閉鎖、プロトタイプチェーン、約束などの概念を導入します。これにより、柔軟性と非同期プログラミング機能が向上します。

さまざまなJavaScriptエンジンは、各エンジンの実装原則と最適化戦略が異なるため、JavaScriptコードを解析および実行するときに異なる効果をもたらします。 1。語彙分析:ソースコードを語彙ユニットに変換します。 2。文法分析:抽象的な構文ツリーを生成します。 3。最適化とコンパイル:JITコンパイラを介してマシンコードを生成します。 4。実行:マシンコードを実行します。 V8エンジンはインスタントコンピレーションと非表示クラスを通じて最適化され、Spidermonkeyはタイプ推論システムを使用して、同じコードで異なるパフォーマンスパフォーマンスをもたらします。

現実世界におけるJavaScriptのアプリケーションには、サーバー側のプログラミング、モバイルアプリケーション開発、モノのインターネット制御が含まれます。 2。モバイルアプリケーションの開発は、ReactNativeを通じて実行され、クロスプラットフォームの展開をサポートします。 3.ハードウェアの相互作用に適したJohnny-Fiveライブラリを介したIoTデバイス制御に使用されます。

私はあなたの日常的な技術ツールを使用して機能的なマルチテナントSaaSアプリケーション(EDTECHアプリ)を作成しましたが、あなたは同じことをすることができます。 まず、マルチテナントSaaSアプリケーションとは何ですか? マルチテナントSaaSアプリケーションを使用すると、Singの複数の顧客にサービスを提供できます

この記事では、許可によって保護されたバックエンドとのフロントエンド統合を示し、next.jsを使用して機能的なedtech SaaSアプリケーションを構築します。 FrontEndはユーザーのアクセス許可を取得してUIの可視性を制御し、APIリクエストがロールベースに付着することを保証します


ホットAIツール

Undresser.AI Undress
リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover
写真から衣服を削除するオンライン AI ツール。

Undress AI Tool
脱衣画像を無料で

Clothoff.io
AI衣類リムーバー

AI Hentai Generator
AIヘンタイを無料で生成します。

人気の記事

ホットツール

ゼンドスタジオ 13.0.1
強力な PHP 統合開発環境

SublimeText3 Linux 新バージョン
SublimeText3 Linux 最新バージョン

AtomエディタMac版ダウンロード
最も人気のあるオープンソースエディター

SublimeText3 Mac版
神レベルのコード編集ソフト(SublimeText3)

VSCode Windows 64 ビットのダウンロード
Microsoft によって発売された無料で強力な IDE エディター
