的retry_strategy是接收对象作为参数包括的功能重试尝试,total_retry_time指示它是最后连接的时间之后经过的时间,由于该错误到的连接丢失,并且数量的times_connected总共。
如果此函数返回一个数字,下一次重试将在该时间之后仅以毫秒为单位进行,如果您发送一个非数字,则不会再进行重试。
retry_strategy: funciton(options)
创建一个名为“ retryStrategy.js ”的文件并复制以下代码。创建文件后,使用命令“ node retryStrategy.js ”运行此代码,如下例所示
// retry_strategy 属性演示示例 // 导入redis模块 const redis = require("redis"); // 使用 retry_strategy 创建 redis 客户端 const client = redis.createClient({ retry_strategy: function(options) { if (options.error && options.error.code === "ECONNREFUSED") { // 如果redis拒绝连接或者无法连接 return new Error("The server refused the connection"); } if (options.total_retry_time > 1000 * 60 * 60) { // 在指定的时间限制后结束重新连接 return new Error("Retry time exhausted"); } if (options.attempt > 10) { // 以内置错误结束重新连接 return undefined; } // 重新连接后 return Math.min(options.attempt * 100, 3000); }, }); console.log("连接创建成功!") client.set("key", "nhooo"); // 这将返回一个 JavaScript 字符串 client.get("key", function(err, reply) { console.log(reply); });输出结果
Connection created successfully! nhooo
如果无法与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) atSocket.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)