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(): Promise { 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 (keys: string[]): Promise > { 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 = {}; 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 (value: T, ttl: number = this.defaultTTL): Promise { 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 (keyValuePairs: Record , ttl: number = this.defaultTTL, batchSize = 1000): Promise { try { const entries = Object.entries(keyValuePairs); for (let i = 0; i (fallbackFn: () => Promise , ttl: number = this.defaultTTL): Promise { try { if (!this.currentKey) { throw new Error('Key is required'); } const cachedValue = await this.getValue (); 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 { 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 { 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 { 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 { if (cacheManager.redisClient) { await cacheManager.redisClient.quit(); } } }
부인 성명: 제공된 모든 리소스는 부분적으로 인터넷에서 가져온 것입니다. 귀하의 저작권이나 기타 권리 및 이익이 침해된 경우 자세한 이유를 설명하고 저작권 또는 권리 및 이익에 대한 증거를 제공한 후 이메일([email protected])로 보내주십시오. 최대한 빨리 처리해 드리겠습니다.
Copyright© 2022 湘ICP备2022001581号-3