如何在Go中获取空闲和“活动”连接的数量?

时间:2018-07-13 03:10:12

标签: go

假设我在Go中有一个常规的HTTP服务器。如何获得当前空闲和活动的TCP连接?

Select your_columns, 
group_concat(d.error_code) from 
your_table group by session_id;

1 个答案:

答案 0 :(得分:3)

创建一个类型以对响应服务器connection state的更改而打开的连接进行计数:

type ConnectionWatcher struct {
    n int64
}

// OnStateChange records open connections in response to connection
// state changes. Set net/http Server.ConnState to this method
// as value.
func (cw *ConnectionWatcher) OnStateChange(conn net.Conn, state http.ConnState) {
    switch state {
    case http.StateNew:
        atomic.AddInt64(&cw.n, 1)
    case http.StateHijacked, http.StateClosed:
        atomic.AddInt64(&cw.n, -1)
    }
}

// Count returns the number of connections at the time
// the call.    
func (cw *ConnectionWatcher) Count() int {
    return int(atomic.LoadInt64(&cw.n))
}

配置网络服务器以使用method value

var cw ConnectionWatcher
s := &http.Server{
   ConnState: cw.OnStateChange
}

使用ListenAndServeServe或这些方法的TLS变体启动服务器。

致电cw.Count()获取打开的连接数。

Run it on the playground