doucao8982 2016-07-04 01:12
浏览 69
已采纳

如何停止正在侦听RethinkDB changefeeds的goroutine?

I am trying to figure out how to use RethinkDB changefeeds with golang. My specific question is how to stop a goroutine that listens for changes to the database. See, for example, the function getData() below. I run this from a handler function by calling go getData(c). Whenever the database updates, the record is passed to the channel c, which is then passed to the handler function and sent to the client using SSE technology. My question is: when the client disconnects, I know how to stop and exit the handler function; however the goroutine that is running the getData() function, keeps running. What can I do to close it? One solution I can think of based on other answers on stackoverflow is to send a signal to close the goroutine on another channel and use a select statement to handle this signal. For example, I can replace

    for cur.Next(&rec) {
        c <- rec
    }

in the function definition below with:

    for cur.Next(&rec) {
        select {
         case <- closesignal:
            return
         default:
            c <- rec
        }
    }

where, closesignal is another channel that is given as a third argument to getData() and a message is sent on this channel by the handler when the client disconnects.

The problem with this approach is: what if the result of the specific rethinkdb query never updates. In that case, the for cur.Next(&rec) loop will not be entered and the closesignal will not be used. Would this goroutine then keep running? If so, how do I stop this goroutine?

The getData() function

func getData(session *r.Session, c chan interface{}) {
    var rec interface{}

    changesOpts := r.ChangesOpts{
        IncludeInitial: true,
    }

    cur, err := r.DB(DBNAME).Table("test").Changes(changesOpts).Run(session)
    if err != nil {
        log.Println(err)
        return
    }
    defer cur.Close()

    defer func() {
        fmt.Println("exiting getData goroutine()...")
    }()


    for cur.Next(&rec) {
        c <- rec
    }

}
  • 写回答

2条回答 默认 最新

  • duanjian4150 2016-07-04 20:23
    关注

    You can stop a goroutine that is listening to a changefeed by closing the cursor. For example this code will listen to a changefeed for 10 seconds before closing:

    go func() {
        time.Sleep(10 * time.Second)
        cur.Close()
    }()
    
    for cur.Next(&rec) {
        c <- rec
    }
    
    // Loop exits as the cursor has been closed
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥100 连续两帧图像高速减法
  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写