Google Pubsub的Go绑定经常被卡住,如下所述。我们几天前就遇到过这个问题。为了找出原因,我编写了一个非常简单的程序,如下所示,仅调用Exists()
并查看它是否在一分钟后返回:
package main
import (
"fmt"
"io/ioutil"
"os"
"time"
"cloud.google.com/go/pubsub"
"golang.org/x/net/context"
"golang.org/x/oauth2/google"
"golang.org/x/oauth2/jwt"
"google.golang.org/api/option"
)
func initializeCredential() *jwt.Config {
keyFile := ...
jsonKey, err := ioutil.ReadFile(keyFile)
if err != nil {
panic(keyFile)
}
jwtConfig, err := google.JWTConfigFromJSON(jsonKey, pubsub.ScopePubSub)
if err != nil {
panic(jsonKey)
}
return jwtConfig
}
func createContext(section string) (context.Context, func()) {
duration := time.Duration(1) * time.Minute
ctx, cancel := context.WithTimeout(context.Background(), duration)
started := time.Now()
d := func() {
elapsed := time.Since(started)
fmt.Printf("%s: elapsed %+v\n", section, elapsed)
if ctx.Err() == context.DeadlineExceeded {
fmt.Fprintf(os.Stderr, "deadline exceeded: %s\n", section)
}
cancel()
}
return ctx, d
}
func newClient(jwtConfig *jwt.Config) *pubsub.Client {
var opts []option.ClientOption
if jwtConfig != nil {
opts = append(opts, option.WithTokenSource(jwtConfig.TokenSource(context.Background())))
}
ctx, finalize := createContext("create-client")
defer finalize()
client, err := pubsub.NewClient(ctx, "project-id", opts...)
if err != nil {
panic("client")
}
return client
}
func useSubscription(client *pubsub.Client) {
ctx, finalize := createContext("use-sub")
defer finalize()
subs := client.Subscription("sub-name")
_, err := subs.Exists(ctx)
if err != nil {
panic("subs")
}
}
func main() {
jwtConfig := initializeCredential()
client := newClient(jwtConfig)
useSubscription(client)
}
令人惊讶的是,我看到很多失败(即“存在()不会在一分钟内返回”。我每2分钟运行一次这个程序20次,成功率低于50%!我不禁想到Go绑定中有一个bug。有没有人遇到类似的问题?
该计划在GCP的美中中心地区运行。所以,我猜不应该有任何网络问题。