我正在尝试测试golang如何处理大负载,以将其与我们目前使用Java制作的应用程序进行比较。
我所做的是像这样的简单回显休息服务(我仅添加代码的重要部分):
// Return default message for root routing
func Index(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path))
}
// Main function
func main() {
router := mux.NewRouter() //.StrictSlash(true)
router.HandleFunc("/", Index).Methods("GET")
router.HandleFunc("/echo/{message}", echoHandler(calledServiceURL)).Methods("GET")
log.Println("Running server....")
log.Fatal(http.ListenAndServe(port, router))
}
我使用ab工具进行了测试,它与-c 500 -n 500一起使用时效果很好,但是当我尝试像这样的大负载进行测试时
ab -c 500 -n 50000 http://localhost:9596/echo/javier
该过程在几秒钟内运行良好,但是当我收到以下错误消息时,它似乎关闭了tcp连接:
Benchmarking localhost (be patient)
apr_socket_recv: Connection reset by peer (54)
Total of 501 requests completed
是由于我的测试达到了操作系统限制还是golang应用程序可以处理的限制?
是否有更好的方法来处理请求,然后避免程序关闭连接? (队列请求之类的东西)。
预先感谢 J
答案 0 :(得分:1)
您碰巧使用OSX吗?我了解ab在OSX上已损坏。
您可以尝试的另一种方法是使用-k来使用keep alive标志,但这可能不是您想要的。
50000也接近接口上的最大套接字数,因此套接字可能已耗尽。套接字不能直接重用,因为它们将处于TIME_WAIT状态一两分钟。确切值可能因操作系统和配置而异。
但是,代码对我来说也很好。
以下代码对我来说很好:
package main
import (
"fmt"
"github.com/gorilla/mux"
"log"
"net/http"
)
func Echo(w http.ResponseWriter, r *http.Request) {
v := mux.Vars(r)
fmt.Fprintf(w, "Echo %v", v["message"])
}
func main() {
router := mux.NewRouter() //.StrictSlash(true)
router.HandleFunc("/echo/{message}", Echo).Methods("GET")
log.Println("Running server....")
log.Fatal(http.ListenAndServe("localhost:8080", router))
}
并给出以下结果:
ab -c 500 -n 50000 localhost:8080/echo/foobar
This is ApacheBench, Version 2.3 <$Revision: 1807734 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/
Benchmarking localhost (be patient)
Completed 5000 requests
Completed 10000 requests
Completed 15000 requests
Completed 20000 requests
Completed 25000 requests
Completed 30000 requests
Completed 35000 requests
Completed 40000 requests
Completed 45000 requests
Completed 50000 requests
Finished 50000 requests
Server Software:
Server Hostname: localhost
Server Port: 8080
Document Path: /echo/foobar
Document Length: 12 bytes
Concurrency Level: 500
Time taken for tests: 2.471 seconds
Complete requests: 50000
Failed requests: 0
Total transferred: 6450000 bytes
HTML transferred: 600000 bytes
Requests per second: 20233.39 [#/sec] (mean)
Time per request: 24.712 [ms] (mean)
Time per request: 0.049 [ms] (mean, across all concurrent requests)
Transfer rate: 2548.93 [Kbytes/sec] received
Connection Times (ms)
min mean[+/-sd] median max
Connect: 0 18 122.8 3 1034
Processing: 0 5 14.9 4 225
Waiting: 0 4 14.7 3 222
Total: 1 24 132.7 6 1245
Percentage of the requests served within a certain time (ms)
50% 6
66% 7
75% 7
80% 7
90% 12
95% 20
98% 30
99% 1040
100% 1245 (longest request)
这是在Ubuntu 18.04上执行的。