duange2971 2019-09-14 11:20
浏览 71

有什么办法可以防止默认的golang程序完成

I have a server working with websocket connections and a database. Some users can connect by sockets, so I need to increment their "online" in db; and at the moment of their disconnection I also decrement their "online" field in db. But in case the server breaks down I use a local variable replica map[string]int of users online. So I need to postpone the server shutdown until it completes a database request that decrements all users "online" in accordance with my variable replica, because at this way socket connection doesnt send default "close" event.

I have found a package github.com/xlab/closer that handles some system calls and can do some action before program finished, but my database request doesnt work in this way (code below)

func main() {
  ...
  // trying to handle program finish event
  closer.Bind(cleanupSocketConnections(&pageHandler))
  ...
}

// function that handles program finish event
func cleanupSocketConnections(p *controllers.PageHandler) func() {
    return func() {
        p.PageService.ResetOnlineUsers()
    }
}

// this map[string]int contains key=userId, value=count of socket connections
type PageService struct {
    Users map[string]int
}

func (p *PageService) ResetOnlineUsers() {
    for userId, count := range p.Users {
        // decrease online of every user in program variable
        InfoService{}.DecreaseInfoOnline(userId, count)
    }
}

Maybe I use it incorrectly or may be there is a better way to prevent default program finish?

  • 写回答

2条回答 默认 最新

  • duanguan5922 2019-09-15 13:58
    关注

    I think that you need to look at go routines and channel.
    Here something (maybe) useful:
    https://nathanleclaire.com/blog/2014/02/15/how-to-wait-for-all-goroutines-to-finish-executing-before-continuing/

    评论

报告相同问题?

悬赏问题

  • ¥35 平滑拟合曲线该如何生成
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集