登录
首页 >  Golang >  Go问答

使用 context.WithCancel 来控制每个会话心跳的开始和结束

来源:stackoverflow

时间:2024-02-08 22:45:22 324浏览 收藏

对于一个Golang开发者来说,牢固扎实的基础是十分重要的,golang学习网就来带大家一点点的掌握基础知识点。今天本篇文章带大家了解《使用 context.WithCancel 来控制每个会话心跳的开始和结束》,主要介绍了,希望对大家的知识积累有所帮助,快点收藏起来吧,否则需要时就找不到了!

问题内容

我目前正在为 typedb 实现 golang 客户端,并且正在努力应对基于会话的心跳约定。通常,您为每个客户端实现心跳,因此相对简单,只需在后台运行一个 goroutine 并每隔几秒发送一次心跳即可。

然而,typedb 选择在每个会话的基础上实现心跳(他们称之为脉冲)。这意味着,每次创建新会话时,我都必须开始使用单独的 goroutine 监视该会话。相反,如果客户端关闭会话,我就必须停止监视。特别难看的是,我还必须每隔一段时间检查一次停滞的会话。切换到每个客户端心跳时存在 gh 问题,但没有 eta,因此我必须使会话心跳正常工作以防止服务端会话终止。

到目前为止,我的解决方案:

  1. 创建新会话
  2. 打开该会话并检查是否有错误
  3. 如果没有错误,将会话添加到以会话 id 为键控的哈希图中

目前看来这可行。代码,仅用于上下文:

https://github.com/marvin-hansen/typedb-client-go/blob/main/src/client/v2/manager_session.go

为了监控每个会话,我正在考虑两个问题:

  1. chanel 关闭多个 goroutine 有点棘手,可能会导致竞争条件。

  2. 我需要某种错误组来捕获心跳故障,即在服务器关闭或网络链接错误的情况下。

考虑到所有这些,我相信 context.withcancel 可能是安全且理智的解决方案。

到目前为止我想到的是:

  1. 将全局上下文作为参数传递给心跳函数
  2. 为每个调用心跳的会话创建一个新的上下文 withcancel
  3. 在 goroutine 中运行心跳,直到调用 cancel(通过 stopmonitoring)或发生错误

我不太清楚的是,如何跟踪从每个跟踪会话返回的所有取消函数,以确保我正在关闭与要关闭的会话匹配的正确 gorotuine?

感谢您提供解决此问题的任何提示。

代码:

func (s SessionManager) startMonitorSession(sessionID []byte) {
    // How do I track each goRoutine per session

}

func (s SessionManager) stopMonitorSession(sessionID []byte) {
    // How do I call the correct cancel function to stop the GoRoutine matching the session?
}

func (s SessionManager) runHeartbeat(ctx context.Context, sessionID []byte) context.CancelFunc {

    // Create a new context, with its cancellation function from the original context
    ctx, cancel := context.WithCancel(ctx)
    go func() {
        select {
        case <-ctx.Done():
            fmt.Println("Stopped monitoring session: ")
        default:
            err := s.sendPulseRequest(sessionID)
            // If this operation returns an error
            // cancel all operations using this local context created above
            if err != nil {
                cancel()
            }
            fmt.Println("done")
        }
    }()

    // return cancel function for call site to close at a later stage
    return cancel
}

func (s SessionManager) sendPulseRequest(sessionID []byte) error {
    mtd := "sendPulse: "

    req := requests.GetSessionPulseReq(sessionID)
    res, pulseErr := s.client.client.SessionPulse(s.client.ctx, req)
    if pulseErr != nil {
        dbgPrint(mtd, "Heartbeat error. Close session")
        return pulseErr
    }
    if res.Alive == false {
        dbgPrint(mtd, "Server not alive anymore. Close session")
        closeErr := s.CloseSession(sessionID)
        if closeErr != nil {
            return closeErr
        }
    }

    // no error
    return nil
}

更新:

感谢评论,我通过将 session 和 cancelfunc 包装在一个名为 typedbsession 的专用结构中,成功解决了大部分问题。

这样,stop 函数只需从结构体中提取 cancelfunc,调用它,然后停止监视 goroutine。经过一些更多的调整,测试似乎通过了,尽管目前这不是并发安全的。

话虽如此,这是一个需要解决的重要问题。再次感谢您的评论!

如果有人愿意建议一些代码改进,特别是为了使这种并发安全,请随时在此处发表评论或填写 gh 问题/pr。

会话类型:

https://github.com/marvin-hansen/typedb-client-go/blob/main/src/client/v2/manager_session_type.go

会话监控:

https://github.com/marvin-hansen/typedb-client-go/blob/main/src/client/v2/manager_session_monitor.go

测试:

https://github.com/marvin-hansen/typedb-client-go/tree/main/test/client/session


正确答案


我的两分钱:

  1. 您可能需要重复运行心跳。在选择周围使用 for 和 time.Ticker
  2. 存储地图会话 ID —> func() 来跟踪所有可取消的上下文。也许你应该将 id 转换为字符串

到这里,我们也就讲完了《使用 context.WithCancel 来控制每个会话心跳的开始和结束》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>