我对GRPC比较陌生,我想确定我正在正确地使用golang进行连接管理。我不想为每个请求创建一个新的连接,但我也不想在扩展时造成瓶颈。
我在init函数中创建了一个连接:
var userConn *grpc.ClientConn
var userServiceName string
func init() {
userServiceName := os.Getenv("USER_SERVICE_URL")
if userServiceName == "" {
userServiceName = "localhost"
}
logging.LogDebug("userClient: Connecting to: "+userServiceName, "")
tempConn, err := grpc.Dial(userServiceName, grpc.WithInsecure())
if err != nil {
logging.LogEmergency("account_user_client.Init() Could not get the connection. "+err.Error(), "")
return
}
userConn = tempConn
}
然后,对于每个函数,我都使用这个连接来创建一个Client:
c := user.NewUserClient(userConn)
// Contact the server and print out its response.
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
r, err := c.GetUserFromTokenID(ctx, &user.GetUserFromTokenRequest{TransactionID: transactionID, OathToken: *oathToken})
//Handle Error and Response
这是处理GRPC连接的一种可接受的方法吗?或者说有更好的方法吗?
十分感谢。