Use the asynchronous calls feature

更新时间:
复制 MD 格式

Classic SDK for Go supports asynchronous calls, allowing you to send API requests without blocking the current thread.

Enable the asynchronous calls feature

Classic SDK for Go provides two methods to enable asynchronous calls. After you enable asynchronous calls, you must call Shutdown() before you can enable them again.

  1. Enable the asynchronous calls feature when you initialize a client.

    import (
        "github.com/aliyun/alibaba-cloud-sdk-go/sdk"
        "github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials"
        "github.com/aliyun/alibaba-cloud-sdk-go/services/ecs"
    )
    
    c := sdk.NewConfig()
    c.EnableAsync = true // Enable the asynchronous calls feature.
    c.GoRoutinePoolSize = 10 // Configure the number of goroutines.
    c.MaxTaskQueueSize = 20 // Configure the maximum number of tasks for a single goroutine.
    c.Timeout = 10 * time.Second
    credential := credentials.NewAccessKeyCredential("acesskeyid", "accesskeysecret")
    client, err := ecs.NewClientWithOptions("regionid", c, credential)
  2. Enable the asynchronous calls feature when you call EnableAsync.

    // Configure the number of goroutines.
    // Configure the maximum number of tasks for a single goroutine.
    // You can call EnableAsync only once. If you want to call EnableAsync again, you must call Shutdown() to disable the asynchronous calls feature.
    client.EnableAsync(10, 20)

Initiate an asynchronous call

Classic SDK for Go provides two methods to initiate an asynchronous call.

  1. Use a channel to return a response.

    responseChannel, errChannel := client.FooWithChan(request)
    
    // this will block
    response := <-responseChannel
    err = <-errChannel
  2. Use the callback function to return a response.

    blocker := client.FooWithCallback(request, func(response *FooResponse, err error) {
        // handle the response and err
    })
    
    // The blocker is of the (chan int) type and is used to control synchronization. If the response is 1, the operation is successful. If the response is 0, the operation failed.
    // If <-blocker returns 0, the operation failed and the error message is passed to the callback function by using err.
    result := <-blocker

Disable the asynchronous calls feature

Call Shutdown() to disable asynchronous calls and close the goroutines.

client.Shutdown()