gpt4 book ai didi

go - 如何在Go中获取空闲和 “active”连接的数量?

转载 作者:行者123 更新时间:2023-12-01 20:21:52 26 4
gpt4 key购买 nike

假设我在Go中有一个常规的HTTP Server。如何获得当前空闲和 Activity 的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)
}

最佳答案

创建一个类型以计算响应于服务器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))
}
配置net.Server以使用 method value:
var cw ConnectionWatcher
s := &http.Server{
ConnState: cw.OnStateChange
}
使用 ListenAndServeServe或这些方法的TLS变体启动服务器。
调用 cw.Count()以获取打开的连接数。
Run it on the playground

关于go - 如何在Go中获取空闲和 “active”连接的数量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51317122/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com