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

mat*_*tes 8 go

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

httpServer := &http.Server{
    Handler: newHandler123(),
}

l, err := net.Listen("tcp", ":8080")
if err != nil {
    log.Fatal(err)
}

err = httpServer.Serve(l)
if err != nil {
    log.Fatal(err)
}
Run Code Online (Sandbox Code Playgroud)

Cer*_*món 11

创建一个类型来计算响应服务器连接状态更改的打开连接数:

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:
        cw.Add(1)
    case http.StateHijacked, http.StateClosed:
        cw.Add(-1)
    }
}

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

// Add adds c to the number of active connections. 
func (cw *ConnectionWatcher) Add(c int64) {
    atomic.AddInt64(&cw.n, c)
}
Run Code Online (Sandbox Code Playgroud)

配置 net.Server 以使用方法值

var cw ConnectionWatcher
s := &http.Server{
   ConnState: cw.OnStateChange
}
Run Code Online (Sandbox Code Playgroud)

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

调用cw.Count()以获取打开的连接数。

在操场上运行它

此代码不监视从 net/http 服务器劫持的连接。最值得注意的是,WebSocket 连接被从服务器劫持。要监视 WebSocket 连接,应用程序应cw.Add(1)在成功升级到 WebSocket 协议并cw.Add(-1)关闭 WebSocket 连接后调用。