All Products
Search
Document Center

Alibaba Cloud SDK:Configure a retry mechanism

Last Updated:Jul 08, 2024

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

Note

In Alibaba Cloud SDK V2.0, the API request processing logic includes the built-in retry logic for network exceptions. When a network exception occurs, the system automatically retries to reinitiate the request to ensure service stability and reliability. If an error is returned due to a business logic error, such as a parameter error or unavailable resources, the system performs no retries. In this case, you must adjust the request based on the corresponding error information instead of performing retries.

Methods

Note

The priority levels of methods that are used to configure a retry mechanism are listed in descending order: use RuntimeOptions and use the default retry settings.

  • We recommend that you use the default retry settings. 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.

  • Configure a retry mechanism by using RuntimeOptions.

    package main
    
    import (
    	"encoding/json"
    	"fmt"
    	"os"
    
    	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
    	ecs20140526 "github.com/alibabacloud-go/ecs-20140526/v4/client"
    	util "github.com/alibabacloud-go/tea-utils/v2/service"
    	"github.com/alibabacloud-go/tea/tea"
    )
    
    func main() {
    	config := &openapi.Config{
    		// Obtain the AccessKey ID of the Resource Access Management (RAM) user from environment variables.
    		AccessKeyId: tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")),
    		// Obtain the AccessKey secret of the RAM user from environment variables.
    		AccessKeySecret: tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")),
    		// Region ID
    		RegionId: tea.String("<RegionId>"),
    	}
    	client, _err := ecs20140526.NewClient(config)
    	if _err != nil {
    		panic(_err)
    	}
    	describeRegionsRequest := &ecs20140526.DescribeRegionsRequest{}
    	// Create a RuntimeObject instance and configure runtime parameters. 
    	runtime := &util.RuntimeOptions{}
    	// Enable the automatic retry mechanism.
    	runtime.Autoretry = tea.Bool(true)
    	// Specify the maximum number of automatic retries.
    	runtime.MaxAttempts = tea.Int(3)
    	resp, _err := client.DescribeRegionsWithOptions(describeRegionsRequest, runtime)
    	if _err != nil {
    		panic(_err)
    	}
    	// The response, which contains the body and headers that are returned by the server.
    	body, err := json.Marshal(resp.Body)
    	if err != nil {
    		panic(err)
    	}
    	fmt.Printf("body: %s\n", string(body))
    }