登录
首页 >  Golang >  Go问答

获取 Go 中的连接数信息(空闲和活动)的方法

来源:stackoverflow

时间:2024-03-24 14:30:38 214浏览 收藏

在 Go 中,我们可以使用一个自定义类型 `connectionwatcher` 来计算当前空闲和活动的 TCP 连接数。这个类型响应服务器连接状态的变化,根据连接状态添加或移除连接数。为了使用它,需要将 `connectionwatcher` 的 `OnStateChange` 方法设置为 net/http 服务器的 `ConnState` 属性。启动服务器后,可以通过调用 `cw.count()` 方法获取打开的连接数。

问题内容

假设我在 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)
}

解决方案


创建一个类型来计算响应服务器 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:
        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)
}

配置net.server使用method value

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

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

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

Run it on the playground

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

以上就是《获取 Go 中的连接数信息(空闲和活动)的方法》的详细内容,更多关于的资料请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>