根据 gRPC 文档,客户端可以指定截止日期,以确定客户端在出现DEADLINE_EXCEEDED
错误退出之前将在服务器上等待多长时间。该文档提到不同的语言有不同的实现,并且某些语言没有默认值。
事实上,在Go gRPC 文档中快速 CTRL+F 显示“截止日期”没有任何结果。我确实发现WithTimeout
了 TCP 连接的拨号器上的一个。
实现如下(来自helloworld 示例):
package main
import (
"log"
"os"
"time"
"golang.org/x/net/context"
"google.golang.org/grpc"
pb "google.golang.org/grpc/examples/helloworld/helloworld"
)
const (
address = "localhost:50051"
defaultName = "world"
deadline = 20
)
func main() {
// Set up a connection to the server with a timeout
conn, err := grpc.Dial(address, grpc.WithInsecure(), grpc.WithTimeout(time.Duration(deadline)*time.Second)
if err != nil {
log.Fatalf("did not connect: %v", err)
}
defer conn.Close()
c := pb.NewGreeterClient(conn)
// Contact the server and print out its response.
name := defaultName
if len(os.Args) > 1 {
name = os.Args[1]
}
r, err := c.SayHello(context.Background(), &pb.HelloRequest{Name: name})
if err != nil {
log.Fatalf("could not greet: %v", err)
}
log.Printf("Greeting: %s", r.Message)
}
Run Code Online (Sandbox Code Playgroud)
仅当客户端在 20 秒后无法连接时,代码才会引发错误。输出将如下所示:
2016/05/24 09:02:54 grpc: Conn.resetTransport failed to create client transport: connection error: desc = "transport: dial tcp [::1]:3265: getsockopt: connection refused"; Reconnecting to "localhost:3265"
2016/05/24 09:02:54 Failed to dial localhost:3265: grpc: timed out trying to connect; please retry.
2016/05/24 09:02:54 could not greet: rpc error: code = 2 desc = grpc: the client connection is closing
Run Code Online (Sandbox Code Playgroud)
正如问题标题中所指出的,我正在使用的系统是点对点的,所以没有中央的、始终启动的服务器,因此 gRPC 实现的重试系统非常棒。但是,我实际上是在寻找截止日期,因为如果远程确实连接了,但服务器需要 20 秒以上的时间来响应,则WithTimeout
上下文中不会引发异常。
对我来说完全获胜将是超时/截止日期系统,其中:
不过我的感觉是,我需要将连接管理和 gRPC 截止日期管理结合起来。有谁知道如何在 Go 中实现截止日期?
您应该更仔细地查看context
包装。GRPC 是用上下文作为其基本部分构建的。您可能需要根据相关信息构建grpc.Dial
上下文和上下文,但这应该相当简单。client.SayHello
归档时间: |
|
查看次数: |
11459 次 |
最近记录: |