Go 中每个处理程序方法的并发连接数
Number of concurrent connection per handler method in Go
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" 有多少个并发连接?
该代码的目标是实现反向代理功能。但是,我也想根据连接到的每个服务器的并发连接添加平衡负载。
非常感谢!
一种方法是通过显式计算并发调用的数量来估算此数字。这可能还不够,因为它只能告诉您 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
的并发调用数。如果这足够了,它可能需要扩展以跟踪每个 server/handler 的容量。
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" 有多少个并发连接?
该代码的目标是实现反向代理功能。但是,我也想根据连接到的每个服务器的并发连接添加平衡负载。
非常感谢!
一种方法是通过显式计算并发调用的数量来估算此数字。这可能还不够,因为它只能告诉您 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
的并发调用数。如果这足够了,它可能需要扩展以跟踪每个 server/handler 的容量。