


Boost your Node.js app performance with a versatile, easy-to-use cache manager built on ioredis. Simplify caching, optimize efficiency, and streamline operations.
I've developed a class built on top of ioredis for my own needs, focusing on ease of use and performance. It includes TypeScript support and aims for straightforward usage and efficient operation. It can still be improved and optimized further, with possibilities for dynamic database usage and more detailed error handling. I'd like to share it with you, and I'd appreciate any feedback or suggestions for enhancements.
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>
The above is the detailed content of Building a High-Performance Cache Manager in Node.js with TypeScript and ioredis. For more information, please follow other related articles on the PHP Chinese website!

Detailed explanation of JavaScript string replacement method and FAQ This article will explore two ways to replace string characters in JavaScript: internal JavaScript code and internal HTML for web pages. Replace string inside JavaScript code The most direct way is to use the replace() method: str = str.replace("find","replace"); This method replaces only the first match. To replace all matches, use a regular expression and add the global flag g: str = str.replace(/fi

This tutorial shows you how to integrate a custom Google Search API into your blog or website, offering a more refined search experience than standard WordPress theme search functions. It's surprisingly easy! You'll be able to restrict searches to y

So here you are, ready to learn all about this thing called AJAX. But, what exactly is it? The term AJAX refers to a loose grouping of technologies that are used to create dynamic, interactive web content. The term AJAX, originally coined by Jesse J

This article series was rewritten in mid 2017 with up-to-date information and fresh examples. In this JSON example, we will look at how we can store simple values in a file using JSON format. Using the key-value pair notation, we can store any kind

Leverage jQuery for Effortless Web Page Layouts: 8 Essential Plugins jQuery simplifies web page layout significantly. This article highlights eight powerful jQuery plugins that streamline the process, particularly useful for manual website creation

Core points This in JavaScript usually refers to an object that "owns" the method, but it depends on how the function is called. When there is no current object, this refers to the global object. In a web browser, it is represented by window. When calling a function, this maintains the global object; but when calling an object constructor or any of its methods, this refers to an instance of the object. You can change the context of this using methods such as call(), apply(), and bind(). These methods call the function using the given this value and parameters. JavaScript is an excellent programming language. A few years ago, this sentence was

jQuery is a great JavaScript framework. However, as with any library, sometimes it’s necessary to get under the hood to discover what’s going on. Perhaps it’s because you’re tracing a bug or are just curious about how jQuery achieves a particular UI

This post compiles helpful cheat sheets, reference guides, quick recipes, and code snippets for Android, Blackberry, and iPhone app development. No developer should be without them! Touch Gesture Reference Guide (PDF) A valuable resource for desig


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Linux new version
SublimeText3 Linux latest version

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

Atom editor mac version download
The most popular open source editor

SublimeText3 Mac version
God-level code editing software (SublimeText3)
