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条)

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题