我是 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
}
然后对于每个函数,我将使用该连接创建一个客户端:
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 连接的可接受方式吗?关于更好的方法有什么建议吗?
繁花不似锦
叮当猫咪
相关分类