Go

时间:2019-04-19 14:36:19

标签: http go proxy connection

func handleForServer1(res http.ResponseWriter, req *http.Request) {
    rPayload := parseRequestBody(req)
    serve("http://server1:8080", res, req)
}

func handleForServer2(res http.ResponseWriter, req *http.Request) {
    rPayload := parseRequestBody(req)
    serve("http://server2:8080", res, req)
}

func serve(dest string, res http.ResponseWriter, req *http.Request) {
    url, _ := url.Parse(dest)
    p := httputil.NewSingleHostReverseProxy(url)

    req.URL.Host = url.Host
    req.URL.Scheme = url.Scheme
    req.Header.Set("X-Forwarded-Host", req.Header.Get("Host"))
    req.Host = url.Host

    p.ServeHTTP(res, req)
}

我有类似上面的代码。 我想知道是否有办法找出处理程序“ handleForServe2”具有多少个并发连接?

该代码的目标是实现反向代理功能。但是,我还要基于每个连接到的服务器的并发连接来添加余额负载。

非常感谢您!

1 个答案:

答案 0 :(得分:3)

一种方法可能是通过显式计算并发调用的数量来近似此数字。这可能还不够,因为它只能告诉您调用handleForServe2的次数。为了说明:

mu sync.RWMutex
concurrentInvocations := 0

func handleForServer2(res http.ResponseWriter, req *http.Request) {
    mu.Lock()
    concurrentInvocations++
    mu.Unlock()

    defer func() {
       mu.Lock()
       concurrentInvocations--
       mu.Unlock()
    }()

    rPayload := parseRequestBody(req)
    serve("http://server2:8080", res, req)
}
ticker := time.NewTicker(5 * time.Second)
for {
   select {
     case <- ticker.C:
       mu.RLock()
       fmt.Printf("Current %d concurrent requests\n", concurrentInvocations)
       mu.RUnlock()
   }
}

现在,您应该可以随时查看handleForServer2的并发调用数。如果足够的话,可能需要扩展它以跟踪每个服务器/处理程序的容量。