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 关于#java#的问题:找一份能快速看完mooc视频的代码
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!