Timeout

Example:timeout

The timeout pattern prevents remote procedure calls from waiting indefinitely for a response. A timeout specifies how long the RPC has to return. If there is no response by the timeout, the RPC invokes a fallback mechanism, whether it’s retrying the request, throwing an exception, or something else. This pattern is perhaps the most basic, fundamental resilience pattern used in RPCs.

Server

You can use OptionFn to set servers' readTimeout and writeTimeout.

```go server structtype Server struct { …… readTimeout time.Duration writeTimeout time.Duration ……}

  1. `OptionFn` methods are:
  2. ```go
  3. func WithReadTimeout(readTimeout time.Duration) OptionFn
  4. func WithWriteTimeout(writeTimeout time.Duration) OptionFn

Client

There are two methods to set timeout for client.

One is set read/write deadline for connections and another is using context.Context.

read/write deadline

Client's Option has three options to set timeout:

  1. type Option struct {
  2. ……
  3. //ConnectTimeout sets timeout for dialing
  4. ConnectTimeout time.Duration
  5. // ReadTimeout sets readdeadline for underlying net.Conns
  6. ReadTimeout time.Duration
  7. // WriteTimeout sets writedeadline for underlying net.Conns
  8. WriteTimeout time.Duration
  9. ……
  10. }

DefaultOption sets the ConnectTimeout to 10 seconds but has not set ReadTimeout and WriteTimeout. If the timeout has not been set, there is no timeout for accessing.

context.Context

context.Context since Go 1.7 can be used to control timeout.

You need to use context.WithTimeout to wrap a go context to invoke client.

  1. func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc)

By smallnest updated 2018-03-27 11:12:10

原文:

http://doc.rpcx.site/part3/timeout.html