在构建启用了重试的云函数时,如何实现增量退避



我正在尝试构建一个将数据加载到API中的谷歌云函数。 他们的指南展示了如何避免无限重试 (https://cloud.google.com/functions/docs/bestpractices/retries#functions-tips-retry-node6( 的示例,但我找不到解释如何实现增量退避的指南。

如果 API 出现故障,GCP 函数似乎会尽快重试。 理想的选择是随着重试计数的增加而增加延迟。

没有人有代码示例(节点(来实现这一点? 如果没有代码,解释或攻击计划也会有所帮助。

研究了文档无济于事。

https://cloud.google.com/functions/docs/bestpractices/retries#set_an_end_condition_to_avoid_infinite_retry_loops

 /**
 * Background Cloud Function that only executes within
 * a certain time period after the triggering event
 *
 * @param {object} event The Cloud Functions event.
 * @param {function} callback The callback function.
 */
exports.avoidInfiniteRetries = (event, callback) => {
  const eventAge = Date.now() - Date.parse(event.timestamp);
  const eventMaxAge = 10000;
  // Ignore events that are too old
  if (eventAge > eventMaxAge) {
    console.log(`Dropping event ${event} with age ${eventAge} ms.`);
    callback();
    return;
  }
  // Do what the function is supposed to do
  console.log(`Processing event ${event} with age ${eventAge} ms.`);
  callback();
};

似乎该功能将始终被强制重试。但是,您可以确保在退避间隔中调用函数的实际重要部分。

只需执行以下操作:

if(eventAge < 1000 && eventAge > 0)
{
   //Do stuff
}else if (eventAge < 3000 && eventAge > 1000) {
   // Do stuff
}(...)
else{
 return;
}

这样,您的实际代码将仅在您通过逻辑设置的时间间隔内执行。

除了您查看的官方文档。你可以尝试查看此文档 [1],即使它指定用于云 IoT 核心版。您会发现不同的示例取决于您的运行时环境。这可能有助于说明如何实现指数退避。

[1] https://cloud.google.com/iot/docs/how-tos/exponential-backoff

检查GCS的文档,有一个关于截断指数退避的很好的解释。

然而,更有趣的是,它指出:

Google Cloud Client Library for Node.js可以自动使用 使用自动重试参数重试请求的退避策略。

因此,挖掘任何随机@google-cloud库并寻找该选项,我们被定向到这段处理退休的代码。

由于该代码在 Apache 许可证 2.0 下,我假设您可以复制该代码片段,只要您遵守许可证限制。

最新更新