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)

最後更新於:24-11-2021

3K+ 次瀏覽

啟動你 事業

透過完成課程獲得認證

開始
廣告
© . All rights reserved.