doutan1637 2019-06-07 03:10
浏览 108
已采纳

闲置一段时间后,如何使Go的http.Server退出?

I am writing a web server in Go using the standard library net/http package that makes use of systemd socket activation.

I have the basics working such that the server is started the first time a connection is made to the listening socket, and I can perform a graceful shutdown when signalled (i.e. so systemctl stop will work without cutting off active requests).

What I would like is for the server to automatically exit when it has been idle for some period of time. Something like the following:

  1. when the last active request completes, start a timer for say 30 seconds.
  2. if any new request arrives during that period, stop the timer.
  3. if the timer expires, perform a graceful shutdown.

The idea being to release the resources the server was using, in the knowledge that systemd will start us again when a new client turns up.

It's parts (1) and (2) that I'm not sure about. Ideally I'd like a solution that doesn't involve modifying all the registered handlers too.

  • 写回答

1条回答 默认 最新

  • dongmiao4733 2019-06-08 08:14
    关注

    Using @CeriseLimón's suggestion, the following helper type seems to do the trick:

    type IdleTracker struct {
        mu     sync.Mutex
        active map[net.Conn]bool
        idle   time.Duration
        timer  *time.Timer
    }
    
    func NewIdleTracker(idle time.Duration) *IdleTracker {
        return &IdleTracker{
            active: make(map[net.Conn]bool),
            idle:   idle,
            timer:  time.NewTimer(idle),
        }
    }
    
    func (t *IdleTracker) ConnState(conn net.Conn, state http.ConnState) {
        t.mu.Lock()
        defer t.mu.Unlock()
    
        oldActive := len(t.active)
        switch state {
        case http.StateNew, http.StateActive, http.StateHijacked:
            t.active[conn] = true
            // stop the timer if we transitioned to idle
            if oldActive == 0 {
                t.timer.Stop()
            }
        case http.StateIdle, http.StateClosed:
            delete(t.active, conn)
            // Restart the timer if we've become idle
            if oldActive > 0 && len(t.active) == 0 {
                t.timer.Reset(t.idle)
            }
        }
    }
    
    func (t *IdleTracker) Done() <-chan time.Time {
        return t.timer.C
    }
    

    Assigning its ConnState method to the server's ConnState member will track whether the server is busy, and signal us when we've been idle for the requested amount of time:

    idle := NewIdleTracker(5 * time.Second)
    server.ConnState = idle.ConnState
    
    go func() {
        <-idle.Done()
        if err := server.Shutdown(context.Background()); err != nil {
            log.Fatalf("error shutting down: %v
    ", err)
        }
    }()
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办