← Concurrent | Asynchronous Call(中文) | Package Management →
Alibaba Cloud Go SDK supports opening asynchronous calls in two ways:
Note: After opening the asynchronous call, you need to call Shutdown()
before you can start the asynchronous call again
-
Enable asynchronous call when initializing
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 // Asynchronous task switch c.GoRoutinePoolSize = 10 // Number of goroutines c.MaxTaskQueueSize = 20 // 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)
-
Enable asynchronous call when calling
EnableAsync
// the first parameter is the maximum number of goroutines // the second parameter is the maximum number of tasks for a single goroutine // EnableAsync is only allowed to be called once, unless the Shutdown() method is used to first close the asynchronous call, and then call EnableAsync client.EnableAsync(10, 20)
Alibaba Cloud Go SDK supports asynchronous calls in two ways:
-
Using channel as return values
responseChannel, errChannel := client.FooWithChan(request) // this will block response := <-responseChannel err = <-errChannel
-
Use callback to control the callback
blocker := client.FooWithCallback(request, func(response *FooResponse, err error) { // handle the response and err }) // blocker which is type of (chan int),is used to control synchronization,when returning 1 means success,and returning 0 means failure. // When <-blocker returns failure,err also will be handled by afferent callback. result := <-blocker
Use the function of client
to close asynchronous call and the goroutines
client.Shutdown()
← Concurrent | Asynchronous Call(中文) | Package Management →