Node.js – retry_strategy 属性在 Redis 中
retry_strategy 是一个函数,它接收对象作为参数,包括重试尝试、total_retry_time(表示上次连接后经过的时间)、连接断开的错误以及总连接次数。
如果此函数返回了一个数字,则下一个重试将在仅在该时间(以毫秒为单位)之后进行,如果你发送一个非数字,则不会进行进一步的重试。
语法
retry_strategy: funciton(options)
示例 1
创建一个名为“retryStrategy.js”的文件,并复制以下代码。创建文件后,使用“node retryStrategy.js”命令来运行此代码,如下面示例中所示
// retry_strategy Property Demo Example // Importing the redis module const redis = require("redis"); // Creating redis client with retry_strategy const client = redis.createClient({ retry_strategy: function(options) { if (options.error && options.error.code === "ECONNREFUSED") { // If redis refuses the connection or is not able to connect return new Error("The server refused the connection"); } if (options.total_retry_time > 1000 * 60 * 60) { // End reconnection after the specified time limit return new Error("Retry time exhausted"); } if (options.attempt > 10) { // End reconnecting with built in error return undefined; } // reconnect after return Math.min(options.attempt * 100, 3000); }, }); console.log("Connection created successfully !") client.set("key", "TutorialsPoint"); // This will return a JavaScript String client.get("key", function(err, reply) { console.log(reply); });
输出
Connection created successfully! TutorialsPoint
如果无法与 Redis 建立连接,就会抛出以下错误。
Error: Redis connection in broken state: retry aborted. at RedisClient.connection_gone (/home/redis/node_modules/redis/index.js:569:30) at RedisClient.on_error (/home/redis/node_modules/redis/index.js:346:10) at Socket.<anonymous> (/home/redis/node_modules/redis/index.js:223:14) at Socket.emit (events.js:198:13) at emitErrorNT (internal/streams/destroy.js:91:8) at emitErrorAndCloseNT (internal/streams/destroy.js:59:3) at process._tickCallback (internal/process/next_tick.js:63:19)
广告