{"id":53296,"date":"2024-12-03T11:31:20","date_gmt":"2024-12-03T03:31:20","guid":{"rendered":"https:\/\/fwq.ai\/blog\/53296\/"},"modified":"2024-12-03T11:31:20","modified_gmt":"2024-12-03T03:31:20","slug":"%e4%bd%bf%e7%94%a8-typescript-%e5%92%8c-ioredis-%e5%9c%a8-nodejs-%e4%b8%ad%e6%9e%84%e5%bb%ba%e9%ab%98%e6%80%a7%e8%83%bd%e7%bc%93%e5%ad%98%e7%ae%a1%e7%90%86%e5%99%a8","status":"publish","type":"post","link":"https:\/\/fwq.ai\/blog\/53296\/","title":{"rendered":"\u4f7f\u7528 TypeScript \u548c ioredis \u5728 Nodejs \u4e2d\u6784\u5efa\u9ad8\u6027\u80fd\u7f13\u5b58\u7ba1\u7406\u5668"},"content":{"rendered":"<p><b><\/b>     <\/p>\n<h1>\u4f7f\u7528 TypeScript \u548c ioredis \u5728 Nodejs \u4e2d\u6784\u5efa\u9ad8\u6027\u80fd\u7f13\u5b58\u7ba1\u7406\u5668<\/h1>\n<p><span style=\"cursor: pointer\"><i><\/i>\u6536\u85cf<\/span>    <\/p>\n<p>\u4f60\u5728\u5b66\u4e60<span style=\"color: #FF6600;, Helvetica, Arial, sans-serif;font-size: 14px;background-color: #FFFFFF\">\u6587\u7ae0<\/span>\u76f8\u5173\u7684\u77e5\u8bc6\u5417\uff1f\u672c\u6587<span style=\"color: #FF6600;, Helvetica, Arial, sans-serif;font-size: 14px;background-color: #FFFFFF\">\u300a\u4f7f\u7528 TypeScript \u548c ioredis \u5728 Nodejs \u4e2d\u6784\u5efa\u9ad8\u6027\u80fd\u7f13\u5b58\u7ba1\u7406\u5668\u300b<\/span>\uff0c\u4e3b\u8981\u4ecb\u7ecd\u7684\u5185\u5bb9\u5c31\u6d89\u53ca\u5230<span style=\"color: #FF6600;, Helvetica, Arial, sans-serif;font-size: 14px;background-color: #FFFFFF\"><\/span>\uff0c\u5982\u679c\u4f60\u60f3\u63d0\u5347\u81ea\u5df1\u7684\u5f00\u53d1\u80fd\u529b\uff0c\u5c31\u4e0d\u8981\u9519\u8fc7\u8fd9\u7bc7\u6587\u7ae0\uff0c\u5927\u5bb6\u8981\u77e5\u9053\u7f16\u7a0b\u7406\u8bba\u57fa\u7840\u548c\u5b9e\u6218\u64cd\u4f5c\u90fd\u662f\u4e0d\u53ef\u6216\u7f3a\u7684\u54e6\uff01<\/p>\n<p><img decoding=\"async\" src=\"https:\/\/www.17golang.com\/uploads\/20241128\/173280567267488428bbedb.jpg\" class=\"aligncenter\" title=\"\u4f7f\u7528 TypeScript \u548c ioredis \u5728 Nodejs \u4e2d\u6784\u5efa\u9ad8\u6027\u80fd\u7f13\u5b58\u7ba1\u7406\u5668\u63d2\u56fe\" alt=\"\u4f7f\u7528 TypeScript \u548c ioredis \u5728 Nodejs \u4e2d\u6784\u5efa\u9ad8\u6027\u80fd\u7f13\u5b58\u7ba1\u7406\u5668\u63d2\u56fe\" \/><\/p>\n<p>\u4f7f\u7528\u57fa\u4e8e ioredis \u6784\u5efa\u7684\u591a\u529f\u80fd\u3001\u6613\u4e8e\u4f7f\u7528\u7684\u7f13\u5b58\u7ba1\u7406\u5668\u6765\u63d0\u5347 node.js \u5e94\u7528\u7a0b\u5e8f\u7684\u6027\u80fd\u3002\u7b80\u5316\u7f13\u5b58\u3001\u4f18\u5316\u6548\u7387\u5e76\u7b80\u5316\u64cd\u4f5c\u3002<\/p>\n<p>\u6211\u6839\u636e\u81ea\u5df1\u7684\u9700\u6c42\u5f00\u53d1\u4e86\u4e00\u4e2a\u57fa\u4e8e ioredis \u7684\u7c7b\uff0c\u91cd\u70b9\u5173\u6ce8\u6613\u7528\u6027\u548c\u6027\u80fd\u3002\u5b83\u5305\u62ec typescript \u652f\u6301\uff0c\u65e8\u5728\u5b9e\u73b0\u7b80\u5355\u4f7f\u7528\u548c\u9ad8\u6548\u64cd\u4f5c\u3002\u5b83\u4ecd\u7136\u53ef\u4ee5\u8fdb\u4e00\u6b65\u6539\u8fdb\u548c\u4f18\u5316\uff0c\u53ef\u4ee5\u52a8\u6001\u6570\u636e\u5e93\u4f7f\u7528\u548c\u66f4\u8be6\u7ec6\u7684\u9519\u8bef\u5904\u7406\u3002\u6211\u60f3\u4e0e\u60a8\u5206\u4eab\uff0c\u5982\u679c\u60a8\u6709\u4efb\u4f55\u53cd\u9988\u6216\u6539\u8fdb\u5efa\u8bae\uff0c\u6211\u5c06\u4e0d\u80dc\u611f\u6fc0\u3002<\/p>\n<pre>import Redis, { type RedisOptions } from 'ioredis';\n\ninterface CacheConfig {\n    defaultTTL?: number;\n}\n\nexport class cacheManager {\n    private static instance: cacheManager;\n    private static redisClient: Redis;\n    private currentKey: string | null;\n    private defaultTTL: number;\n\n    private static readonly DEFAULT_TTL = 3600;\n\n    private constructor(config?: CacheConfig) {\n        const redisConfig: RedisOptions = {\n            db: 2,\n            retryStrategy: (times: number) =&gt; {\n                const delay = Math.min(times * 50, 2000);\n                return delay;\n            },\n            lazyConnect: true,\n            maxRetriesPerRequest: 3,\n            enableReadyCheck: true,\n            autoResubscribe: true,\n            autoResendUnfulfilledCommands: true,\n            reconnectOnError: (err: Error) =&gt; {\n                const targetError = 'READONLY';\n                return err.message.includes(targetError);\n            },\n        };\n\n        if (!cacheManager.redisClient) {\n            cacheManager.redisClient = new Redis(redisConfig);\n\n            cacheManager.redisClient.on('error', (error: Error) =&gt; {\n                console.error('Redis Client Error:', error);\n            });\n\n            cacheManager.redisClient.on('connect', () =&gt; {\n                console.debug('Redis Client Connected');\n            });\n\n            cacheManager.redisClient.on('ready', () =&gt; {\n                console.debug('Redis Client Ready');\n            });\n        }\n\n        this.currentKey = null;\n        this.defaultTTL = config?.defaultTTL ?? cacheManager.DEFAULT_TTL;\n    }\n\n    public static getInstance(config?: CacheConfig): cacheManager {\n        if (!cacheManager.instance) {\n            cacheManager.instance = new cacheManager(config);\n        }\n        return cacheManager.instance;\n    }\n\n    public key(key: string): cacheManager {\n        this.validateKey(key);\n        this.currentKey = key;\n        return this;\n    }\n\n    private validateKey(key: string): void {\n        if (key.length &gt; 100) throw new Error('Key too long');\n        if (!\/^[\\w:-]+$\/.test(key)) throw new Error('Invalid key format');\n    }\n\n    public async getValue&lt;T&gt;(): Promise&lt;T | null&gt; {\n        try {\n            if (!this.currentKey) {\n                throw new Error('Key is required');\n            }\n            const value = await cacheManager.redisClient.get(this.currentKey);\n            return value ? JSON.parse(value) : null;\n        } catch (error) {\n            console.error('getValue Error:', error);\n            return null;\n        }\n    }\n\n    public async getMultiple&lt;T&gt;(keys: string[]): Promise&lt;Record&lt;string, T | null&gt;&gt; {\n        try {\n            const pipeline = cacheManager.redisClient.pipeline();\n            for (const key of keys) {\n                pipeline.get(key);\n            }\n\n            type PipelineResult = [Error | null, string | null][] | null;\n            const results = (await pipeline.exec()) as PipelineResult;\n            const output: Record&lt;string, T | null&gt; = {};\n\n            if (!results) {\n                return output;\n            }\n\n            keys.forEach((key, index) =&gt; {\n                const result = results[index];\n                if (result) {\n                    const [err, value] = result;\n                    if (!err &amp;&amp; value) {\n                        try {\n                            output[key] = JSON.parse(value);\n                        } catch {\n                            output[key] = null;\n                        }\n                    } else {\n                        output[key] = null;\n                    }\n                } else {\n                    output[key] = null;\n                }\n            });\n\n            return output;\n        } catch (error) {\n            console.error('getMultiple Error:', error);\n            return {};\n        }\n    }\n\n    public async setValue&lt;T&gt;(value: T, ttl: number = this.defaultTTL): Promise&lt;boolean&gt; {\n        try {\n            if (!this.currentKey) {\n                throw new Error('Key is required');\n            }\n            const stringValue = JSON.stringify(value);\n\n            if (ttl) {\n                await cacheManager.redisClient.setex(this.currentKey, ttl, stringValue);\n            } else {\n                await cacheManager.redisClient.set(this.currentKey, stringValue);\n            }\n\n            return true;\n        } catch (error) {\n            console.error('setValue Error:', error);\n            return false;\n        }\n    }\n\n    public async setBulkValue&lt;T&gt;(keyValuePairs: Record&lt;string, T&gt;, ttl: number = this.defaultTTL, batchSize = 1000): Promise&lt;boolean&gt; {\n        try {\n            const entries = Object.entries(keyValuePairs);\n            for (let i = 0; i &lt; entries.length; i += batchSize) {\n                const batch = entries.slice(i, i + batchSize);\n                const pipeline = cacheManager.redisClient.pipeline();\n\n                for (const [key, value] of batch) {\n                    const stringValue = JSON.stringify(value);\n                    if (ttl) {\n                        pipeline.setex(key, ttl, stringValue);\n                    } else {\n                        pipeline.set(key, stringValue);\n                    }\n                }\n\n                await pipeline.exec();\n            }\n            return true;\n        } catch (error) {\n            console.error('setBulkValue Error:', error);\n            return false;\n        }\n    }\n\n    public async getOrSetValue&lt;T&gt;(fallbackFn: () =&gt; Promise&lt;T&gt;, ttl: number = this.defaultTTL): Promise&lt;T | null&gt; {\n        try {\n            if (!this.currentKey) {\n                throw new Error('Key is required');\n            }\n\n            const cachedValue = await this.getValue&lt;T&gt;();\n\n            if (cachedValue !== null) {\n                return cachedValue;\n            }\n\n            const value = await fallbackFn();\n            await this.setValue(value, ttl);\n            return value;\n        } catch (error) {\n            console.error('getOrSetValue Error:', error);\n            return null;\n        }\n    }\n\n    public async delete(): Promise&lt;boolean&gt; {\n        try {\n            if (!this.currentKey) {\n                throw new Error('Key is required');\n            }\n            await cacheManager.redisClient.del(this.currentKey);\n            return true;\n        } catch (error) {\n            console.error('delete Error:', error);\n            return false;\n        }\n    }\n\n    public async exists(): Promise&lt;boolean&gt; {\n        try {\n            if (!this.currentKey) {\n                throw new Error('Key is required');\n            }\n            return (await cacheManager.redisClient.exists(this.currentKey)) === 1;\n        } catch (error) {\n            console.error('exists Error:', error);\n            return false;\n        }\n    }\n\n    public async getTTL(): Promise&lt;number&gt; {\n        try {\n            if (!this.currentKey) {\n                throw new Error('Key is required');\n            }\n            return await cacheManager.redisClient.ttl(this.currentKey);\n        } catch (error) {\n            console.error('getTTL Error:', error);\n            return -1;\n        }\n    }\n\n    public static async disconnect(): Promise&lt;void&gt; {\n        if (cacheManager.redisClient) {\n            await cacheManager.redisClient.quit();\n        }\n    }\n}\n\n<\/pre>\n<p>\u597d\u4e86\uff0c\u672c\u6587\u5230\u6b64\u7ed3\u675f\uff0c\u5e26\u5927\u5bb6\u4e86\u89e3\u4e86\u300a\u4f7f\u7528 TypeScript \u548c ioredis \u5728 Nodejs \u4e2d\u6784\u5efa\u9ad8\u6027\u80fd\u7f13\u5b58\u7ba1\u7406\u5668\u300b\uff0c\u5e0c\u671b\u672c\u6587\u5bf9\u4f60\u6709\u6240\u5e2e\u52a9\uff01\u5173\u6ce8\u7c73\u4e91\u516c\u4f17\u53f7\uff0c\u7ed9\u5927\u5bb6\u5206\u4eab\u66f4\u591a\u6587\u7ae0\u77e5\u8bc6\uff01<\/p>\n<p>      \u7248\u672c\u58f0\u660e \u672c\u6587\u8f6c\u8f7d\u4e8e\uff1adev.to \u5982\u6709\u4fb5\u72af\uff0c\u8bf7\u8054\u7cfb\u5220\u9664    <\/p>\n<dl>\n<dt><\/dt>\n<dd>\n   R-Tree \u5982\u4f55\u9ad8\u6548\u5730\u5b9e\u73b0\u7a7a\u95f4\u7d22\u5f15\uff1f\n <\/dd>\n<\/dl>\n","protected":false},"excerpt":{"rendered":"<p>\u4f7f\u7528 TypeScript \u548c ioredis \u5728 Nodejs \u4e2d\u6784\u5efa\u9ad8\u6027\u80fd\u7f13\u5b58\u7ba1\u7406\u5668 \u6536\u85cf \u4f60\u5728\u5b66\u4e60\u6587\u7ae0\u76f8\u5173\u7684\u77e5\u8bc6\u5417\uff1f\u672c\u6587\u300a\u4f7f\u7528 TypeScript \u548c ioredis \u5728 Nodejs \u4e2d\u6784\u5efa\u9ad8\u6027\u80fd\u7f13\u5b58\u7ba1\u7406\u5668\u300b\uff0c\u4e3b\u8981\u4ecb\u7ecd\u7684\u5185\u5bb9\u5c31\u6d89\u53ca\u5230\uff0c\u5982\u679c\u4f60\u60f3\u63d0\u5347\u81ea\u5df1\u7684\u5f00\u53d1\u80fd\u529b\uff0c\u5c31\u4e0d\u8981\u9519\u8fc7\u8fd9\u7bc7\u6587\u7ae0\uff0c\u5927\u5bb6\u8981\u77e5\u9053\u7f16\u7a0b\u7406\u8bba\u57fa\u7840\u548c\u5b9e\u6218\u64cd\u4f5c\u90fd\u662f\u4e0d\u53ef\u6216\u7f3a\u7684\u54e6\uff01 \u4f7f\u7528\u57fa\u4e8e ioredis \u6784\u5efa\u7684\u591a\u529f\u80fd\u3001\u6613\u4e8e\u4f7f\u7528\u7684\u7f13\u5b58\u7ba1\u7406\u5668\u6765\u63d0\u5347 node.js \u5e94\u7528\u7a0b\u5e8f\u7684\u6027\u80fd\u3002\u7b80\u5316\u7f13\u5b58\u3001\u4f18\u5316\u6548\u7387\u5e76\u7b80\u5316\u64cd\u4f5c\u3002 \u6211\u6839\u636e\u81ea\u5df1\u7684\u9700\u6c42\u5f00\u53d1\u4e86\u4e00\u4e2a\u57fa\u4e8e ioredis \u7684\u7c7b\uff0c\u91cd\u70b9\u5173\u6ce8\u6613\u7528\u6027\u548c\u6027\u80fd\u3002\u5b83\u5305\u62ec typescript \u652f\u6301\uff0c\u65e8\u5728\u5b9e\u73b0\u7b80\u5355\u4f7f\u7528\u548c\u9ad8\u6548\u64cd\u4f5c\u3002\u5b83\u4ecd\u7136\u53ef\u4ee5\u8fdb\u4e00\u6b65\u6539\u8fdb\u548c\u4f18\u5316\uff0c\u53ef\u4ee5\u52a8\u6001\u6570\u636e\u5e93\u4f7f\u7528\u548c\u66f4\u8be6\u7ec6\u7684\u9519\u8bef\u5904\u7406\u3002\u6211\u60f3\u4e0e\u60a8\u5206\u4eab\uff0c\u5982\u679c\u60a8\u6709\u4efb\u4f55\u53cd\u9988\u6216\u6539\u8fdb\u5efa\u8bae\uff0c\u6211\u5c06\u4e0d\u80dc\u611f\u6fc0\u3002 import Redis, { type RedisOptions } from &#8216;ioredis&#8217;; interface CacheConfig { defaultTTL?: number; } export class cacheManager { private static instance: cacheManager; private static redisClient: Redis; private currentKey: string | [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[16],"tags":[],"class_list":["post-53296","post","type-post","status-publish","format-standard","hentry","category-16"],"_links":{"self":[{"href":"https:\/\/fwq.ai\/blog\/wp-json\/wp\/v2\/posts\/53296","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/fwq.ai\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/fwq.ai\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/fwq.ai\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/fwq.ai\/blog\/wp-json\/wp\/v2\/comments?post=53296"}],"version-history":[{"count":0,"href":"https:\/\/fwq.ai\/blog\/wp-json\/wp\/v2\/posts\/53296\/revisions"}],"wp:attachment":[{"href":"https:\/\/fwq.ai\/blog\/wp-json\/wp\/v2\/media?parent=53296"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/fwq.ai\/blog\/wp-json\/wp\/v2\/categories?post=53296"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/fwq.ai\/blog\/wp-json\/wp\/v2\/tags?post=53296"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}