与 gRPC 客户端重新连接的正确方法
大家好,今天本人给大家带来文章《与 gRPC 客户端重新连接的正确方法》,文中内容主要涉及到,如果你对Golang方面的知识点感兴趣,那就请各位朋友继续看下去吧~希望能真正帮到你们,谢谢!
我有一个 go grpc 客户端连接到在 k8s 集群中的不同 pod 中运行的 grpc 服务器。
它运行良好,可以接收和处理请求。
我现在想知道在 grpc 服务器 pod 被回收的情况下如何最好地实现弹性。
据我所知,clientconn.go 代码应该自动处理重新连接,但我就是无法让它工作,我担心我的实现在第一个实例中是不正确的。
从 main 调用代码:
go func() { if err := grpcclient.processrequests(); err != nil { log.error("error while processing requests") //do something here?? } }()
我在 grpcclient 包装器模块中的代码:
func (grpcclient *grpcclient) processrequests() error { defer grpcclient.close() for { request, err := reqclient.stream.recv() log.info("request received") if err == io.eof { break } if err != nil { //when pod is recycled, this is what's hit with err: //rpc error: code = unavailable desc = transport is closing" //what is the correct pattern for recovery here so that we can await connection //and continue processing requests once more? //should i return err here and somehow restart the processrequests() go routine in the //main funcition? break } else { //the happy path //code block to process any requests that are received } } return nil } func (reqclient *requestclient) close() { //this is called soon after the conneciton drops reqclient.conn.close() }
编辑: 艾敏·拉莱托维奇(emin laletovic)在下面优雅地回答了我的问题,并且大部分内容都得到了解答。 我必须对 waituntilready 函数进行一些更改:
func (grpcclient *gRPCClient) waitUntilReady() bool { ctx, cancel := context.WithTimeout(context.Background(), 300*time.Second) //define how long you want to wait for connection to be restored before giving up defer cancel() currentState := grpcclient.conn.GetState() stillConnecting := true for currentState != connectivity.Ready && stillConnecting { //will return true when state has changed from thisState, false if timeout stillConnecting = grpcclient.conn.WaitForStateChange(ctx, currentState) currentState = grpcclient.conn.GetState() log.WithFields(log.Fields{"state: ": currentState, "timeout": timeoutDuration}).Info("Attempting reconnection. State has changed to:") } if stillConnecting == false { log.Error("Connection attempt has timed out.") return false } return true }
解决方案
rpc 连接由 clientconn.go
自动处理,但这并不意味着流也会自动处理。
流一旦断开,无论是由于 rpc 连接中断还是其他原因,都无法自动重新连接,一旦 rpc 连接恢复,您需要从服务器获取新的流。
等待 rpc 连接处于 ready
状态并建立新流的伪代码可能如下所示:
func (grpcclient *grpcclient) processrequests() error { defer grpcclient.close() go grpcclient.process() for { select { case <- grpcclient.reconnect: if !grpcclient.waituntilready() { return errors.new("failed to establish a connection within the defined timeout") } go grpcclient.process() case <- grpcclient.done: return nil } } } func (grpcclient *grpcclient) process() { reqclient := getstream() //always get a new stream for { request, err := reqclient.stream.recv() log.info("request received") if err == io.eof { grpcclient.done <- true return } if err != nil { grpcclient.reconnect <- true return } else { //the happy path //code block to process any requests that are received } } } func (grpcclient *grpcclient) waituntilready() bool { ctx, cancel := context.withtimeout(context.background(), 60*time.second) //define how long you want to wait for connection to be restored before giving up defer cancel() return grpcclient.conn.waitforstatechange(ctx, conectivity.ready) }
编辑:
重新审视上面的代码,应该纠正一些错误。 waitforstatechange
函数等待连接状态从传递状态更改,它不等待连接更改为传递状态。
最好跟踪当前连接状态,如果通道空闲,则使用 connect
函数进行连接。
func (grpcclient *grpcclient) processrequests() error { defer grpcclient.close() go grpcclient.process() for { select { case <- grpcclient.reconnect: if !grpcclient.isreconnected(1*time.second, 60*time.second) { return errors.new("failed to establish a connection within the defined timeout") } go grpcclient.process() case <- grpcclient.done: return nil } } } func (grpcclient *grpcclient) isreconnected(check, timeout time.duration) bool { ctx, cancel := context.context.withtimeout(context.background(), timeout) defer cancel() ticker := time.newticker(check) for{ select { case <- ticker.c: grpcclient.conn.connect() if grpcclient.conn.getstate() == connectivity.ready { return true } case <- ctx.done(): return false } } }
当grpc连接关闭时,grpc客户端连接的状态将为
idle
或 transient_failure
。以下是我的 grpc 双向流式传输自定义重新连接机制的示例。首先,我有一个 for 循环来保持重新连接,直到 grpc 服务器启动,在调用 conn.connect()
后状态将变为就绪状态。
for { select { case <-ctx.done(): return false default: if client.conn.getstate() != connectivity.ready { client.conn.connect() } // reserve a short duration (customizable) for conn to change state from idle to ready if grpc server is up time.sleep(500 * time.millisecond) if client.conn.getstate() == connectivity.ready { return true } // define reconnect time interval (backoff) or/and reconnect attempts here time.sleep(2 * time.second) } }
此外,还将生成一个 goroutine 以执行重新连接任务。成功重连后,会生成另一个goroutine来监听grpc服务器。
for { select { case <-ctx.done(): return case <-reconnectch: if client.conn.getstate() != connectivity.ready && *isconnectedwebsocket { if o.waituntilready(client, isconnectedwebsocket, ctx) { err := o.generatenewprocessorderstream(client, ctx) if err != nil { logger.logger.error("failed to establish stream connection to grpc server ...") } // re-listening server side streaming go o.listenprocessorderserverside(client, reconnectch, ctx, isconnectedwebsocket) } } } }
请注意,监听任务是由另一个 goroutine 并发处理的。
// listening server side streaming go o.listenProcessOrderServerSide(client, reconnectCh, websocketCtx, isConnectedWebSocket)
您可以查看我的代码示例 here。希望这会有所帮助。
图片来源:艾敏·拉莱托维奇
好了,本文到此结束,带大家了解了《与 gRPC 客户端重新连接的正确方法》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!

- 上一篇
- 奔驰新款纯电旗舰EQS发布:复古外观,续航大增

- 下一篇
- WIN10设置开机项的操作方法
-
- Golang · Go问答 | 1年前 |
- 在读取缓冲通道中的内容之前退出
- 139浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 戈兰岛的全球 GOPRIVATE 设置
- 204浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 如何将结构作为参数传递给 xml-rpc
- 325浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 如何用golang获得小数点以下两位长度?
- 477浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 如何通过 client-go 和 golang 检索 Kubernetes 指标
- 486浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 将多个“参数”映射到单个可变参数的习惯用法
- 439浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 将 HTTP 响应正文写入文件后出现 EOF 错误
- 357浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 结构中映射的匿名列表的“复合文字中缺少类型”
- 352浏览 收藏
-
- Golang · Go问答 | 1年前 |
- NATS Jetstream 的性能
- 101浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 如何将复杂的字符串输入转换为mapstring?
- 440浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 相当于GoLang中Java将Object作为方法参数传递
- 212浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 如何确保所有 goroutine 在没有 time.Sleep 的情况下终止?
- 143浏览 收藏
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 542次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 508次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 497次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 484次学习
-
- 笔灵AI生成答辩PPT
- 探索笔灵AI生成答辩PPT的强大功能,快速制作高质量答辩PPT。精准内容提取、多样模板匹配、数据可视化、配套自述稿生成,让您的学术和职场展示更加专业与高效。
- 27次使用
-
- 知网AIGC检测服务系统
- 知网AIGC检测服务系统,专注于检测学术文本中的疑似AI生成内容。依托知网海量高质量文献资源,结合先进的“知识增强AIGC检测技术”,系统能够从语言模式和语义逻辑两方面精准识别AI生成内容,适用于学术研究、教育和企业领域,确保文本的真实性和原创性。
- 42次使用
-
- AIGC检测-Aibiye
- AIbiye官网推出的AIGC检测服务,专注于检测ChatGPT、Gemini、Claude等AIGC工具生成的文本,帮助用户确保论文的原创性和学术规范。支持txt和doc(x)格式,检测范围为论文正文,提供高准确性和便捷的用户体验。
- 39次使用
-
- 易笔AI论文
- 易笔AI论文平台提供自动写作、格式校对、查重检测等功能,支持多种学术领域的论文生成。价格优惠,界面友好,操作简便,适用于学术研究者、学生及论文辅导机构。
- 51次使用
-
- 笔启AI论文写作平台
- 笔启AI论文写作平台提供多类型论文生成服务,支持多语言写作,满足学术研究者、学生和职场人士的需求。平台采用AI 4.0版本,确保论文质量和原创性,并提供查重保障和隐私保护。
- 42次使用
-
- GoLand调式动态执行代码
- 2023-01-13 502浏览
-
- 用Nginx反向代理部署go写的网站。
- 2023-01-17 502浏览
-
- Golang取得代码运行时间的问题
- 2023-02-24 501浏览
-
- 请问 go 代码如何实现在代码改动后不需要Ctrl+c,然后重新 go run *.go 文件?
- 2023-01-08 501浏览
-
- 如何从同一个 io.Reader 读取多次
- 2023-04-11 501浏览