Classic SDK for Go, asenkron çağrıları destekler; bu sayede API isteklerini geçerli iş parçacığını engellemeden gönderebilirsiniz.
Asenkron çağrı özelliğini etkinleştirin
Classic SDK for Go, asenkron çağrıları etkinleştirmek için iki yöntem sunar. Asenkron çağrıları etkinleştirdikten sonra, özelliği tekrar etkinleştirebilmek için öncelikle Shutdown() metodunu çağırmanız gerekir.
-
Bir
clientbaşlatırken asenkron çağrı özelliğini etkinleştirin.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) -
EnableAsyncmetodunu çağırırken asenkron çağrı özelliğini etkinleştirin.// 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)
Asenkron çağrı başlatın
Classic SDK for Go, asenkron bir çağrıyı başlatmak için iki yöntem sağlar.
-
Yanıtı döndürmek için kanal (channel) kullanın.
responseChannel, errChannel := client.FooWithChan(request) // this will block response := <-responseChannel err = <-errChannel -
Yanıtı döndürmek için geri arama işlevini (callback function) kullanın.
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
Asenkron çağrı özelliğini devre dışı bırakın
Asenkron çağrıları devre dışı bırakmak ve goroutine'leri kapatmak için Shutdown() metodunu çağırın.
client.Shutdown()