创建 gRPC 客户端连接使用 WithBlock() 选项与异步启动的 gRPC 服务器时,是否会一直阻塞?
来源:stackoverflow
时间:2024-03-24 18:36:46 454浏览 收藏
在使用 `grpc.WithBlock()` 选项时,异步启动的 gRPC 服务器可能无法立即建立客户端连接。虽然该选项旨在阻止 `grpc.Dial()` 立即返回,但它并不保证在连接建立之前返回错误。当连接字符串无效时,连接可能会无限期挂起,导致测试超时。为了确保在连接错误时捕获错误,可以将 `grpc.FailOnNonTempDialError(true)` 与 `grpc.WithBlock()` 一起使用。
我想编写一个单元测试,在其中运行一个临时 grpc 服务器,该服务器在测试中的单独 goroutine 中启动,并在测试运行后停止。为此,我尝试将本教程(https://grpc.io/docs/languages/go/quickstart/)中的“hello,world”示例改编为一个服务器和客户端分开的示例main.go
s,有一个测试函数,它异步启动服务器,然后使用 grpc.withblock()
选项建立客户端连接。
我已将简化的示例放入此存储库中,https://github.com/kurtpeek/grpc-helloworld;这是 main_test.go
:
package main import ( "context" "fmt" "log" "net" "testing" "time" "github.com/stretchr/testify/require" "google.golang.org/grpc" "google.golang.org/grpc/examples/helloworld/helloworld" ) const ( port = ":50051" ) type server struct { helloworld.unimplementedgreeterserver } func (s *server) sayhello(ctx context.context, in *helloworld.hellorequest) (*helloworld.helloreply, error) { log.printf("received: %v", in.getname()) return &helloworld.helloreply{message: "hello " + in.getname()}, nil } func testhelloworld(t *testing.t) { lis, err := net.listen("tcp", port) require.noerror(t, err) s := grpc.newserver() helloworld.registergreeterserver(s, &server{}) go s.serve(lis) defer s.stop() log.println("dialing grpc server...") conn, err := grpc.dial(fmt.sprintf("localhost:%s", port), grpc.withinsecure(), grpc.withblock()) require.noerror(t, err) defer conn.close() c := helloworld.newgreeterclient(conn) ctx, cancel := context.withtimeout(context.background(), time.second) defer cancel() log.println("making grpc request...") r, err := c.sayhello(ctx, &helloworld.hellorequest{name: "john doe"}) require.noerror(t, err) log.printf("greeting: %s", r.getmessage()) }
问题是当我运行这个测试时,它超时了:
> go test -timeout 10s ./... -v === RUN TestHelloWorld 2020/06/30 11:17:45 Dialing gRPC server... panic: test timed out after 10s
我无法理解为什么未建立连接?在我看来,服务器已正确启动...
解决方案
您在此处发布的代码似乎有一个拼写错误:
fmt.sprintf("localhost:%s", 端口)
如果我在没有 grpc.withblock()
选项的情况下运行您的测试函数,c.sayhello
会给出以下错误:
rpc error: code = unavailable desc = connection error: desc = "transport: error while dialing dial tcp: address localhost::50051: too many colons in address"
罪魁祸首似乎是 localhost::50051
从 const
声明(或者从 fmt.sprintf("localhost:%s", port)
,如果您愿意的话)中删除额外的冒号后,测试通过。
const ( port = "50051" // without the colon )
输出:
2020/06/30 23:59:01 dialing grpc server... 2020/06/30 23:59:01 making grpc request... 2020/06/30 23:59:01 received: john doe 2020/06/30 23:59:01 greeting: hello john doe
但是,从grpc.withblock()
的文档来看
如果没有这个,dial 会立即返回并在后台连接服务器。
因此,使用此选项,任何连接错误都应立即从 grpc.dial
调用返回:
conn, err := grpc.dial("bad connection string", grpc.withblock()) // can't connect if err != nil { panic(err) // should panic, right? }
那么为什么你的代码会挂起?
通过查看 grpc
包的源代码(我针对 v1.30.0
构建了测试):
// a blocking dial blocks until the clientconn is ready. if cc.dopts.block { for { s := cc.getstate() if s == connectivity.ready { break } else if cc.dopts.copts.failonnontempdialerror && s == connectivity.transientfailure { if err = cc.connectionerror(); err != nil { terr, ok := err.(interface { temporary() bool }) if ok && !terr.temporary() { return nil, err } } } if !cc.waitforstatechange(ctx, s) { // ctx got timeout or canceled. if err = cc.connectionerror(); err != nil && cc.dopts.returnlasterror { return nil, err } return nil, ctx.err() } }
所以 s
此时确实处于 transientfailure
状态,但是 failonnontempdialerror
选项默认为 false
,并且 waitforstatechange
在上下文过期时为 false,这不会发生,因为 zqbczq bdial 在后台上下文中运行:
// dial creates a client connection to the given target. func dial(target string, opts ...dialoption) (*clientconn, error) { return dialcontext(context.background(), target, opts...) }
此时我不知道这是否是预期行为,因为从 v1.30.0
开始,其中一些 api 被标记为实验性的。
无论如何,最终为了确保您在 dial
上捕获此类错误,您还可以将代码重写为:
conn, err := grpc.Dial( "localhost:50051", grpc.WithTransportCredentials(insecure.NewCredentials()), grpc.FailOnNonTempDialError(true), grpc.WithBlock(), )
如果连接字符串错误,则会立即失败并显示相应的错误消息。
今天关于《创建 gRPC 客户端连接使用 WithBlock() 选项与异步启动的 gRPC 服务器时,是否会一直阻塞?》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!
-
502 收藏
-
502 收藏
-
501 收藏
-
501 收藏
-
501 收藏
-
139 收藏
-
204 收藏
-
325 收藏
-
477 收藏
-
486 收藏
-
439 收藏
-
357 收藏
-
352 收藏
-
101 收藏
-
440 收藏
-
212 收藏
-
143 收藏
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 立即学习 542次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 立即学习 508次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 立即学习 497次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 立即学习 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 立即学习 484次学习