I am using this code to connect to a grpc server and clientConn
object is used for all subsequent rpc calls. maxDelay
is set to 5 seconds. Now because of some issue at server, it is not responding for a grpc call. So my client is waiting for a long time for each rpc call. Do I need to set timeout in a different way?
b := grpc.BackoffConfig{
MaxDelay: maxDelay,
}
clientConn, err := grpc.Dial(serverAddress, grpc.WithBackoffConfig(b), grpc.WithInsecure())
if err != nil {
log.Println("Dial failed!")
return err
}
You can modify your code to add a timeout using grpc.WithTimeout(5 * time.Second)
instead of using MaxDelay
and grpc.WithBackoffConfig(b)
which are for retries and retries delay.
clientConn, err := grpc.Dial(serverAddress, grpc.WithTimeout(5 * time.Second), grpc.WithInsecure())
if err != nil {
log.Println("Dial failed!")
return err
}
However the above is deprecated, alternatively you can use DialContext
and context.WithTimeout
ctx, _ := context.WithTimeout(context.Background(), 5*time.Second)
clientConn, err := grpc.DialContext(ctx, serverAddress, grpc.WithInsecure())
if err != nil {
log.Println("Dial failed!")
return err
}
The doc of WithTimeout
says that it is used to set timeout of connection initializing, and not to set timeout to the calls. context in the DialContext is the same.
WithTimeout returns a DialOption that configures a timeout for dialing a ClientConn initially. This is valid if and only if WithBlock() is present. Deprecated: use DialContext instead of Dial and context.WithTimeout instead. Will be supported throughout 1.x.
To set timeout to the calls you can pass context
to invoke
like:
ctx, cancel := context.WithDeadline(ctx, time.Now().Add(time.Duration(2000)*time.Millisecond))
defer cancel()
clientConn.Invoke(ctx, "/YourEndpoint", in, out, opts...)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With