在使用grpc的时候遇到了一个问题: 如何设置client端的超时时间? 网上搜了一大圈, 没有太明显的例子.
这里我们先看下看看grpc的helloworld例子:
client
1 | func main() { |
稍微跟一下SayHello
的调用, 最后是调用到invoke
函数:
google.golang.org/grpc/call.go
1 | func invoke(ctx context.Context, method string, args, reply interface{}, cc *ClientConn, opts ...CallOption) (e error) { |
这里值得注意的是context的超时设置. 仔细读下context的文档, 会发现context里面有对应的超时设置:
WithTimeout
1 | package main |
我们尝试在client调用之前设置context的超时:
client
1 | func main() { |
为保证超时, 在sever代码中休息一会儿:
server
1 | // SayHello implements helloworld.GreeterServer |
分别运行client和server两个程序, 会看见client端打印:
1 | could not greet: rpc error: code = DeadlineExceeded desc = context deadline exceeded |