重试策略

本页面介绍了 Cloud Storage 工具如何重试失败的请求以及如何自定义重试的行为,还介绍了重试请求的注意事项。

概览

有两个因素决定了能否安全地重试请求:

  1. 您从请求中收到的响应
  2. 请求的幂等性

响应

您从请求收到的响应表明重试请求是否有用。与暂时性问题相关的响应通常可以重试。另一方面,与永久错误相关的响应表明您需要进行更改(例如更改授权或配置),然后重试请求才有用。以下响应表明可用于重试的暂时性问题:

  • HTTP 4084295xx 响应代码。
  • 套接字超时和 TCP 断开连接。

如需了解详情,请参阅 JSONXML 的状态和错误代码。

幂等性

幂等请求意味着请求可以重复执行,并且始终使目标资源处于相同的结束状态。例如,列出请求始终具有幂等性,因为此类请求不会修改资源。另一方面,创建新的 Pub/Sub 通知从不具有幂等性,因为它在每次请求成功时创建新的通知 ID。

以下是使操作具有幂等性的条件示例:

  • 即使持续请求目标资源,操作也会对目标资源产生相同的可观察到的影响。

  • 操作仅成功一次。

  • 操作不会对目标资源的状态产生任何可观察到的影响。

收到可重试响应时,您应该考虑请求的幂等性,因为重试非幂等请求可能会导致竞态条件和其他冲突。

条件式幂等性

一部分请求具有条件式幂等性,这意味着这些请求仅在包含特定可选参数时才具有幂等性。默认情况下,只有在条件情况通过时,才应对重试有条件安全的操作进行重试。Cloud Storage 接受前提条件和 ETag 作为请求的条件情况。

操作的幂等性

下表列出了属于每种幂等性的 Cloud Storage 操作。

幂等性 运维
始终具有幂等性
  • 所有获取和列出请求
  • 插入或删除存储分区
  • 测试存储分区 IAM 政策和权限
  • 锁定保留政策
  • 删除 HMAC 密钥或 Pub/Sub 通知
有条件地具有幂等性
  • 针对将 IfMetagenerationMatch 或 ETag 作为 HTTP 前提条件的存储分区的更新/修补请求
  • 针对将 IfMetagenerationMatch 或 ETag 作为 HTTP 前提条件的对象的更新/修补请求
  • 将 ETag 作为 HTTP 前提条件或在资源正文中设置存储分区 IAM 政策
  • 将 ETag 作为 HTTP 前提条件或在资源正文中更新 HMAC 密钥
  • 使用 ifGenerationMatch 插入、复制、编写或重写对象
  • 使用 ifGenerationMatch 删除对象(对于对象版本,则使用世代编号)
永不幂等
  • 创建 HMAC 密钥
  • 创建 Pub/Sub 通知
  • 创建、删除或发送针对存储分区和对象 ACL 或默认对象 ACL的修补/更新请求

Cloud Storage 工具如何实现重试策略

控制台

Google Cloud 控制台会代表您向 Cloud Storage 发送请求,并处理任何必要的退避操作。

命令行

gcloud storage 命令会重试响应部分中列出的错误,您无需执行其他操作。您可能需要针对其他错误执行操作,例如:

  • 凭据无效或权限不足。

  • 由于代理配置问题,网络不可达。

对于可重试的错误,gcloud CLI 会使用截断的二进制指数退避算法策略重试请求。gcloud CLI 的默认重试次数上限为 32。

客户端库

C++

默认情况下,操作支持针对以下 HTTP 错误代码进行重试,以及针对指示连接丢失或从未成功建立的任何套接字错误进行重试。

  • 408 Request Timeout
  • 429 Too Many Requests
  • 500 Internal Server Error
  • 502 Bad Gateway
  • 503 Service Unavailable
  • 504 Gateway Timeout

C++ 库中的所有指数退避算法和重试设置均可配置。如果库中实施的算法不支持您的需求,您可以提供自定义代码来实现自己的策略。

设置 默认值
自动重试 正确
重试请求的最长时间 15 分钟
初始等待时间(退避时间) 1 秒
每次迭代的等待时间乘数 2
最长等待时间 5 分钟

默认情况下,C++ 库会重试所有具有可重试错误的操作(即使是从不具有幂等性的操作),并且可以在重复尝试成功后删除或创建多个资源。如需仅重试具有幂等性的操作,请使用 google::cloud::storage::StrictIdempotencyPolicy 类。

C#

C# 客户端库默认使用指数退避算法

Go

默认情况下,操作支持重试以下错误:

  • 连接错误:
    • io.ErrUnexpectedEOF:这可能是由于暂时性的网络问题导致的。
    • 包含 connection refusedurl.Error:这可能是由于暂时性的网络问题导致的。
    • 包含 connection reset by peerurl.Error:这意味着 Google Cloud 已重置连接。
    • net.ErrClosed:这意味着 Google Cloud 已关闭连接。
  • HTTP 代码:
    • 408 Request Timeout
    • 429 Too Many Requests
    • 500 Internal Server Error
    • 502 Bad Gateway
    • 503 Service Unavailable
    • 504 Gateway Timeout
  • 实现 Temporary() 接口并赋予值 err.Temporary() == true 的错误
  • 使用 Go 1.13 错误封装封装的上述任何错误

Go 库中的所有指数退避算法设置都是可配置的。默认情况下,Go 中的操作使用以下指数退避算法设置(默认值取自 gax):

设置 默认值(以秒为单位)
自动重试 如果是幂等的,则为 true
尝试次数上限 无限制
初次重试延迟 1 秒
重试延迟乘数 2.0
重试延迟上限 30 秒
总超时(可续传上传数据块) 32 秒
总超时(所有其他操作) 无限制

一般而言,除非控制上下文被取消、客户端关闭或收到非暂时性错误,否则重试将无限期地继续。如需阻止重试继续,请使用上下文超时或取消。此行为的唯一例外情况是使用 Writer 执行可续传上传时,其中数据足够大,需要多个请求。在这种情况下,每个数据块默认超时并在 32 秒后停止重试。您可以通过更改 Writer.ChunkRetryDeadline 来调整默认超时。

一部分 Go 操作属于有条件地幂等(有条件地安全重试)。这些操作仅在满足特定条件时才会重试:

  • GenerationMatchGeneration

    • 如果对调用应用了 GenerationMatch 前提条件或设置了 ObjectHandle.Generation,则重试安全。
  • MetagenerationMatch

    • 如果对调用应用了 MetagenerationMatch 前提条件,则重试安全。
  • Etag

    • 如果方法将 etag 插入到 JSON 请求正文,则重试安全。仅在设置了 HmacKeyMetadata.Etag 时才会在 HMACKeyHandle.Update 中使用。

RetryPolicy 默认设置为 RetryPolicy.RetryIdempotent。如需查看如何修改默认重试行为的示例,请参阅下面的自定义重试部分。

Java

默认情况下,操作支持重试以下错误:

  • 连接错误:
    • Connection reset by peer:这意味着 Google Cloud 已重置连接。
    • Unexpected connection closure:这意味着 Google Cloud 已关闭连接。
  • HTTP 代码:
    • 408 Request Timeout
    • 429 Too Many Requests
    • 500 Internal Server Error
    • 502 Bad Gateway
    • 503 Service Unavailable
    • 504 Gateway Timeout

Java 库中的所有指数退避算法设置都是可配置的。默认情况下,通过 Java 执行的操作会使用以下指数退避算法设置:

设置 默认值(以秒为单位)
自动重试 如果是幂等的,则为 true
尝试次数上限 6
初次重试延迟 1 秒
重试延迟乘数 2.0
重试延迟上限 32 秒
总超时 50 秒
初始远程过程调用 (RPC) 超时 50 秒
远程过程调用 (RPC) 超时乘数 1.0
远程过程调用 (RPC) 超时上限 50 秒
连接超时 20 秒
读取超时 20 秒

如需详细了解上述参数,请参阅 RetrySettings.BuilderHttpTransportOptions.Builder 的 Java 参考文档。

一部分 Java 操作属于有条件地幂等(有条件地安全重试)。这些操作只能在包含特定参数时重试:

  • ifGenerationMatchgeneration

    • 如果已将 ifGenerationMatchgeneration 作为选项传入方法,则重试安全。
  • ifMetagenerationMatch

    • 如果作为选项传入 ifMetagenerationMatch,则重试安全。

StorageOptions.setStorageRetryStrategy 默认设置为 StorageRetryStrategy#getDefaultStorageRetryStrategy。如需查看如何修改默认重试行为的示例,请参阅下面的自定义重试部分。

Node.js

默认情况下,操作支持重试以下错误代码:

  • 连接错误:
    • EAI_again:这是 DNS 查找错误。有关详情,请参见此处
    • Connection reset by peer:这意味着 Google Cloud 已重置连接。
    • Unexpected connection closure:这意味着 Google Cloud 已关闭连接。
  • HTTP 代码:
    • 408 Request Timeout
    • 429 Too Many Requests
    • 500 Internal Server Error
    • 502 Bad Gateway
    • 503 Service Unavailable
    • 504 Gateway Timeout

Node.js 库中的所有指数退避算法设置都是可配置的。 默认情况下,通过 Node.js 执行的操作使用以下指数退避算法设置:

设置 默认值(以秒为单位)
自动重试 如果是幂等的,则为 true
重试次数上限 3
初始等待时间 1 秒
每次迭代的等待时间乘数 2
最长等待时间 64 秒
默认截止时间 600 秒

一部分 Node.js 操作属于有条件地幂等(有条件地安全重试)。这些操作只能在包含特定参数时重试:

  • ifGenerationMatchgeneration

    • 如果已将 ifGenerationMatchgeneration 作为选项传入方法,则重试安全。通常,方法只会接受这两个参数中的一个。
  • ifMetagenerationMatch

    • 如果作为选项传入 ifMetagenerationMatch,则重试安全。

retryOptions.idempotencyStrategy 默认设置为 IdempotencyStrategy.RetryConditional。如需查看如何修改默认重试行为的示例,请参阅下面的自定义重试部分。

PHP

PHP 客户端库默认使用指数退避算法

Python

默认情况下,操作支持重试以下错误代码:

  • 连接错误:
    • requests.exceptions.ConnectionError
    • requests.exceptions.ChunkedEncodingError(仅适用于将载荷数据提取或发送到对象的操作,例如上传和下载)
    • ConnectionError
  • HTTP 代码:
    • 408 Request Timeout
    • 429 Too Many Requests
    • 500 Internal Server Error
    • 502 Bad Gateway
    • 503 Service Unavailable
    • 504 Gateway Timeout

通过 Python 执行的操作使用以下指数退避算法默认设置:

设置 默认值(以秒为单位)
自动重试 如果是幂等的,则为 true
初始等待时间 1
每次迭代的等待时间乘数 2
最长等待时间 60
默认截止时间 120

一部分 Python 操作在包含特定参数时具有条件幂等性(有条件地安全重试)。只有满足条件时,这些操作才会重试:

  • DEFAULT_RETRY_IF_GENERATION_SPECIFIED

    • 如果已将 generationif_generation_match 作为参数传入方法,则重试安全。通常,方法只会接受这两个参数中的一个。
  • DEFAULT_RETRY_IF_METAGENERATION_SPECIFIED

    • 如果已将 if_metageneration_match 作为参数传入方法,则重试安全。
  • DEFAULT_RETRY_IF_ETAG_IN_JSON

    • 如果方法将 etag 插入到 JSON 请求正文,则重试安全。对于 HMACKeyMetadata.update(),这意味着必须对 HMACKeyMetadata 对象本身设置 etag。对于其他类的 set_iam_policy() 方法,这意味着必须在传入方法的“policy”参数中设置 etag。

Ruby

默认情况下,操作支持重试以下错误代码:

  • 连接错误:
    • SocketError
    • HTTPClient::TimeoutError
    • Errno::ECONNREFUSED
    • HTTPClient::KeepAliveDisconnected
  • HTTP 代码:
    • 408 Request Timeout
    • 429 Too Many Requests
    • 5xx Server Error

Ruby 客户端库中的所有指数退避算法设置都是可配置的。默认情况下,通过 Ruby 客户端库执行的操作使用以下指数退避算法设置:

设置 默认值
自动重试 True
重试次数上限 3
初始等待时间 1 秒
每次迭代的等待时间乘数 2
最长等待时间 60 秒
默认截止时间 900 秒

一部分 Ruby 操作在包含特定参数时具有条件幂等性(有条件地安全重试):

  • if_generation_matchgeneration

    • 如果将 generationif_generation_match 参数作为参数传递给方法,则重试安全。通常,方法只会接受这两个参数中的一个。
  • if_metageneration_match

    • 如果将 if_metageneration_match 参数作为选项传入,则重试安全。

默认情况下,系统会重试所有幂等操作,并且仅在条件 case 通过时才会重试有条件的幂等操作。系统不会重试非幂等操作。如需查看如何修改默认重试行为的示例,请参阅下面的自定义重试部分。

REST API

直接调用 JSON 或 XML API 时,您应该使用指数退避算法来实现您自己的重试策略。

自定义重试

控制台

您无法使用 Google Cloud 控制台自定义重试行为。

命令行

对于 gcloud storage 命令,您可以通过创建命名配置并设置以下部分或全部属性来控制重试策略:

  • base_retry_delay
  • exponential_sleep_multiplier
  • max_retries
  • max_retry_delay

然后,您可以使用 --configuration 项目范围标志来按命令应用定义的配置,也可以使用 gcloud config set 命令为所有 gcloud 命令应用定义的配置。

客户端库

C++

如需自定义重试行为,请在初始化 google::cloud::storage::Client 对象时为以下选项提供值:

  • google::cloud::storage::RetryPolicyOption:该库提供 google::cloud::storage::LimitedErrorCountRetryPolicygoogle::cloud::storage::LimitedTimeRetryPolicy 类。您可以提供自己的类,该类必须实现 google::cloud::RetryPolicy 接口。

  • google::cloud::storage::BackoffPolicyOption:该库提供 google::cloud::storage::ExponentialBackoffPolicy 类。您可以提供自己的类,该类必须实现 google::cloud::storage::BackoffPolicy 接口。

  • google::cloud::storage::IdempotencyPolicyOption:库提供 google::cloud::storage::StrictIdempotencyPolicygoogle::cloud::storage::AlwaysRetryIdempotencyPolicy 类。您可以提供自己的类,该类必须实现 google::cloud::storage::IdempotencyPolicy 接口。

如需了解详情,请参阅 C++ 客户端库参考文档

namespace gcs = ::google::cloud::storage;
// Create the client configuration:
auto options = google::cloud::Options{};
// Retries only idempotent operations.
options.set<gcs::IdempotencyPolicyOption>(
    gcs::StrictIdempotencyPolicy().clone());
// On error, it backs off for a random delay between [1, 3] seconds, then [3,
// 9] seconds, then [9, 27] seconds, etc. The backoff time never grows larger
// than 1 minute.
options.set<gcs::BackoffPolicyOption>(
    gcs::ExponentialBackoffPolicy(
        /*initial_delay=*/std::chrono::seconds(1),
        /*maximum_delay=*/std::chrono::minutes(1),
        /*scaling=*/3.0)
        .clone());
// Retries all operations for up to 5 minutes, including any backoff time.
options.set<gcs::RetryPolicyOption>(
    gcs::LimitedTimeRetryPolicy(std::chrono::minutes(5)).clone());
return gcs::Client(std::move(options));

C#

目前,您无法自定义 C# 客户端库使用的默认重试策略。

Go

当您初始化存储客户端时,系统将设置默认的重试配置。除非被替换,否则配置中的选项会设置为默认值。用户可以为单个库调用(使用 BucketHandle.RetryerObjectHandle.Retryer)或一个客户端发出所有调用(使用 Client.SetRetry)配置非默认重试行为。要修改重试行为,请将所需的 RetryOptions 传递给以下方法之一。

如需了解如何自定义重试行为,请参阅以下代码示例。

import (
	"context"
	"fmt"
	"io"
	"time"

	"cloud.google.com/go/storage"
	"github.com/googleapis/gax-go/v2"
)

// configureRetries configures a custom retry strategy for a single API call.
func configureRetries(w io.Writer, bucket, object string) error {
	// bucket := "bucket-name"
	// object := "object-name"
	ctx := context.Background()
	client, err := storage.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("storage.NewClient: %w", err)
	}
	defer client.Close()

	// Configure retries for all operations using this ObjectHandle. Retries may
	// also be configured on the BucketHandle or Client types.
	o := client.Bucket(bucket).Object(object).Retryer(
		// Use WithBackoff to control the timing of the exponential backoff.
		storage.WithBackoff(gax.Backoff{
			// Set the initial retry delay to a maximum of 2 seconds. The length of
			// pauses between retries is subject to random jitter.
			Initial: 2 * time.Second,
			// Set the maximum retry delay to 60 seconds.
			Max: 60 * time.Second,
			// Set the backoff multiplier to 3.0.
			Multiplier: 3,
		}),
		// Use WithPolicy to customize retry so that all requests are retried even
		// if they are non-idempotent.
		storage.WithPolicy(storage.RetryAlways),
	)

	// Use context timeouts to set an overall deadline on the call, including all
	// potential retries.
	ctx, cancel := context.WithTimeout(ctx, 500*time.Second)
	defer cancel()

	// Delete an object using the specified retry policy.
	if err := o.Delete(ctx); err != nil {
		return fmt.Errorf("Object(%q).Delete: %w", object, err)
	}
	fmt.Fprintf(w, "Blob %v deleted with a customized retry strategy.\n", object)
	return nil
}

Java

初始化 Storage 时,也会初始化 RetrySettings 的实例。除非被替换,否则 RetrySettings 中的选项会设置为默认值。要修改默认的自动重试行为,请将自定义 StorageRetryStrategy 传入用于构建 Storage 实例的 StorageOptions。如需修改任何其他标量参数,请将自定义 RetrySettings 传入用于构建 Storage 实例的 StorageOptions

如需了解如何自定义重试行为,请参阅以下示例:


import com.google.api.gax.retrying.RetrySettings;
import com.google.cloud.storage.BlobId;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;
import com.google.cloud.storage.StorageRetryStrategy;
import org.threeten.bp.Duration;

public final class ConfigureRetries {
  public static void main(String[] args) {
    String bucketName = "my-bucket";
    String blobName = "blob/to/delete";
    deleteBlob(bucketName, blobName);
  }

  static void deleteBlob(String bucketName, String blobName) {
    // Customize retry behavior
    RetrySettings retrySettings =
        StorageOptions.getDefaultRetrySettings()
            .toBuilder()
            // Set the max number of attempts to 10 (initial attempt plus 9 retries)
            .setMaxAttempts(10)
            // Set the backoff multiplier to 3.0
            .setRetryDelayMultiplier(3.0)
            // Set the max duration of all attempts to 5 minutes
            .setTotalTimeout(Duration.ofMinutes(5))
            .build();

    StorageOptions alwaysRetryStorageOptions =
        StorageOptions.newBuilder()
            // Customize retry so all requests are retried even if they are non-idempotent.
            .setStorageRetryStrategy(StorageRetryStrategy.getUniformStorageRetryStrategy())
            // provide the previously configured retrySettings
            .setRetrySettings(retrySettings)
            .build();

    // Instantiate a client
    Storage storage = alwaysRetryStorageOptions.getService();

    // Delete the blob
    BlobId blobId = BlobId.of(bucketName, blobName);
    boolean success = storage.delete(blobId);

    System.out.printf(
        "Deletion of Blob %s completed %s.%n", blobId, success ? "successfully" : "unsuccessfully");
  }
}

Node.js

初始化 Cloud Storage 时,系统还会初始化 retryOptions 配置文件。除非被替换,否则配置中的选项会设置为默认值。要修改默认重试行为,请在初始化时将自定义重试配置 retryOptions 传递到存储构造函数中。Node.js 客户端库可以自动使用退避策略来重试带有 autoRetry 参数的请求。

如需了解如何自定义重试行为,请参阅以下代码示例。

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// The ID of your GCS bucket
// const bucketName = 'your-unique-bucket-name';

// The ID of your GCS file
// const fileName = 'your-file-name';

// Imports the Google Cloud client library
const {Storage} = require('@google-cloud/storage');

// Creates a client
const storage = new Storage({
  retryOptions: {
    // If this is false, requests will not retry and the parameters
    // below will not affect retry behavior.
    autoRetry: true,
    // The multiplier by which to increase the delay time between the
    // completion of failed requests, and the initiation of the subsequent
    // retrying request.
    retryDelayMultiplier: 3,
    // The total time between an initial request getting sent and its timeout.
    // After timeout, an error will be returned regardless of any retry attempts
    // made during this time period.
    totalTimeout: 500,
    // The maximum delay time between requests. When this value is reached,
    // retryDelayMultiplier will no longer be used to increase delay time.
    maxRetryDelay: 60,
    // The maximum number of automatic retries attempted before returning
    // the error.
    maxRetries: 5,
    // Will respect other retry settings and attempt to always retry
    // conditionally idempotent operations, regardless of precondition
    idempotencyStrategy: IdempotencyStrategy.RetryAlways,
  },
});
console.log(
  'Functions are customized to be retried according to the following parameters:'
);
console.log(`Auto Retry: ${storage.retryOptions.autoRetry}`);
console.log(
  `Retry delay multiplier: ${storage.retryOptions.retryDelayMultiplier}`
);
console.log(`Total timeout: ${storage.retryOptions.totalTimeout}`);
console.log(`Maximum retry delay: ${storage.retryOptions.maxRetryDelay}`);
console.log(`Maximum retries: ${storage.retryOptions.maxRetries}`);
console.log(
  `Idempotency strategy: ${storage.retryOptions.idempotencyStrategy}`
);

async function deleteFileWithCustomizedRetrySetting() {
  await storage.bucket(bucketName).file(fileName).delete();
  console.log(`File ${fileName} deleted with a customized retry strategy.`);
}

deleteFileWithCustomizedRetrySetting();

PHP

目前,您无法自定义 PHP 客户端库使用的默认重试策略。

Python

如需修改默认重试行为,请使用 with_XXX 方法调用 google.cloud.storage.retry.DEFAULT_RETRY 对象来创建该对象的副本。如果添加 DEFAULT_RETRY 参数,Python 客户端库会自动使用退避时间策略重试请求。

请注意,对于将载荷数据提取或发送到对象的操作(例如上传和下载),系统不支持 with_predicate。建议您逐个修改特性。如需了解详情,请参阅 google-api-core 重试参考文档

如需配置您自己的条件性重试,请创建 ConditionalRetryPolicy 对象,并使用 DEFAULT_RETRY_IF_GENERATION_SPECIFIEDDEFAULT_RETRY_IF_METAGENERATION_SPECIFIEDDEFAULT_RETRY_IF_ETAG_IN_JSON 封装自定义 Retry 对象。

如需了解如何自定义重试行为,请参阅以下代码示例。

from google.cloud import storage
from google.cloud.storage.retry import DEFAULT_RETRY

def configure_retries(bucket_name, blob_name):
    """Configures retries with customizations."""
    # The ID of your GCS bucket
    # bucket_name = "your-bucket-name"
    # The ID of your GCS object
    # blob_name = "your-object-name"

    storage_client = storage.Client()
    bucket = storage_client.bucket(bucket_name)
    blob = bucket.blob(blob_name)

    # Customize retry with a deadline of 500 seconds (default=120 seconds).
    modified_retry = DEFAULT_RETRY.with_deadline(500.0)
    # Customize retry with an initial wait time of 1.5 (default=1.0).
    # Customize retry with a wait time multiplier per iteration of 1.2 (default=2.0).
    # Customize retry with a maximum wait time of 45.0 (default=60.0).
    modified_retry = modified_retry.with_delay(initial=1.5, multiplier=1.2, maximum=45.0)

    # blob.delete() uses DEFAULT_RETRY_IF_GENERATION_SPECIFIED by default.
    # Override with modified_retry so the function retries even if the generation
    # number is not specified.
    print(
        f"The following library method is customized to be retried according to the following configurations: {modified_retry}"
    )

    blob.delete(retry=modified_retry)
    print(f"Blob {blob_name} deleted with a customized retry strategy.")

Ruby

初始化存储客户端时,所有重试配置都会设置为上表中显示的值。如需修改默认重试行为,请在初始化存储客户端时传递重试配置。

如需替换特定操作的重试次数,请在操作的 options 参数中传递 retries

def configure_retries bucket_name: nil, file_name: nil
  # The ID of your GCS bucket
  # bucket_name = "your-unique-bucket-name"

  # The ID of your GCS object
  # file_name = "your-file-name"

  require "google/cloud/storage"

  # Creates a client
  storage = Google::Cloud::Storage.new(

    # The maximum number of automatic retries attempted before returning
    # the error.
    #
    # Customize retry configuration with the maximum retry attempt of 5.
    retries: 5,

    # The total time in seconds that requests are allowed to keep being retried.
    # After max_elapsed_time, an error will be returned regardless of any
    # retry attempts made during this time period.
    #
    # Customize retry configuration with maximum elapsed time of 500 seconds.
    max_elapsed_time: 500,

    # The initial interval between the completion of failed requests, and the
    # initiation of the subsequent retrying request.
    #
    # Customize retry configuration with an initial interval of 1.5 seconds.
    base_interval: 1.5,

    # The maximum interval between requests. When this value is reached,
    # multiplier will no longer be used to increase the interval.
    #
    # Customize retry configuration with maximum interval of 45.0 seconds.
    max_interval: 45,

    # The multiplier by which to increase the interval between the completion
    # of failed requests, and the initiation of the subsequent retrying request.
    #
    # Customize retry configuration with an interval multiplier per iteration of 1.2.
    multiplier: 1.2
  )

  # Uses the retry configuration set during the client initialization above with 5 retries
  file = storage.service.get_file bucket_name, file_name

  # Maximum retry attempt can be overridden for each operation using options parameter.
  storage.service.delete_file bucket_name, file_name, options: { retries: 4 }
  puts "File #{file.name} deleted with a customized retry strategy."
end

REST API

使用指数退避算法实现您自己的重试策略。

指数退避算法

指数退避算法以指数方式重试请求(不断增加各次请求之间的等待时间,直到达到最大退避时间)。您通常应该将指数退避算法与抖动结合使用,以重试同时满足响应和幂等性条件的请求。如需了解使用指数退避算法实现自动重试的最佳做法,请参阅解决级联故障

后续步骤