All Products
Search
Document Center

Alibaba Cloud SDK:Configure a retry mechanism

Last Updated:Jul 02, 2024

This topic describes how to configure a retry mechanism in Alibaba Cloud SDK V2.0.

After you configure a retry mechanism, SDK V2.0 resends an API request if the API request fails due to a network error. SDK V2.0 does not resend an API request if the API request fails due to a service error. The retry mechanism that you configure by using RuntimeOptions takes precedence over the default retry setting. By default, no retries are performed when exceptions occur. If you enable the automatic retry mechanism but do not specify the maximum number of retries, up to three retries are performed by default.

import com.aliyun.ecs20140526.models.DescribeRegionsRequest;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;

public class Sample {
public static void main(String[] args) throws Exception {
        Config config = new com.aliyun.teaopenapi.models.Config();
        // Obtain the AccessKey ID of the Resource Access Management (RAM) user from environment variables.
        config.setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"));
        // Obtain the AccessKey secret of the RAM user from environment variables.
        config.setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
        // The region ID.
        config.setRegionId("<regionId>");
        com.aliyun.ecs20140526.Client client = new com.aliyun.ecs20140526.Client(config);

        // Create a RuntimeOptions instance and configure the retry mechanism. The settings take effect only on the requests that use the RuntimeOptions instance.
        RuntimeOptions runtimeOptions = new RuntimeOptions();
        // Enable the automatic retry mechanism.
        runtimeOptions.autoretry = true;
        // Specify the maximum number of automatic retries.
        runtimeOptions.maxAttempts = 3;

        DescribeRegionsRequest describeRegionsRequest = new DescribeRegionsRequest();

        client.describeRegionsWithOptions(describeRegionsRequest, runtimeOptions);
    }
}