在Go語言中,我們可以使用context包來處理超時。context包提供了一種優雅的方式來處理請求的超時和取消操作。以下是一個使用context.WithTimeout處理超時的示例:
package main
import (
"context"
"fmt"
"time"
"github.com/samuel/go-zookeeper/zk"
)
func main() {
// 連接到Zookeeper集群
connection, _, err := zk.Connect([]string{"127.0.0.1:2181"}, time.Second*5)
if err != nil {
fmt.Printf("Failed to connect to Zookeeper: %v\n", err)
return
}
defer connection.Close()
// 創建一個帶超時的上下文
ctx, cancel := context.WithTimeout(context.Background(), time.Second*3)
defer cancel()
// 使用帶超時的上下文執行操作
err = performOperationWithTimeout(ctx, connection)
if err != nil {
fmt.Printf("Operation failed with timeout: %v\n", err)
} else {
fmt.Println("Operation completed successfully")
}
}
func performOperationWithTimeout(ctx context.Context, connection *zk.Conn) error {
// 在這里執行你的操作,例如獲取節點數據
data, _, err := connection.Get("/some/path")
if err != nil {
return err
}
// 檢查上下文是否已取消或超時
select {
case <-ctx.Done():
return ctx.Err()
default:
// 在這里處理獲取到的數據
fmt.Printf("Received data: %s\n", string(data))
return nil
}
}
在這個示例中,我們首先連接到Zookeeper集群,然后創建一個帶超時的上下文。接下來,我們使用這個帶超時的上下文執行一個操作(例如獲取節點數據)。在操作過程中,我們檢查上下文是否已取消或超時,如果是,則返回相應的錯誤。