I am relatively new to GRPC and want to be sure that I am doing connection management correctly with golang. I don't want to have to create a new connection for every call but I also don't want to create bottlenecks as I scale.
What I did was to create a single connection in the init function:
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
}
And then for each function I will use that connection to create a 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
is this an acceptable way to handle grpc connections? Any recommendations on better ways?
Thank you very much.