我在Golang中写了一个httpserver,但是我发现当来自Web浏览器的多个请求时,http.HandleFunc将被阻塞.如何让服务器同时处理多个请求?谢谢.
我的代码是:
func DoQuery(w http.ResponseWriter,r *http.Request) { r.ParseForm() fmt.Printf("%d path %s\n",time.Now().Unix(),r.URL.Path) time.Sleep(10 * time.Second) fmt.Fprintf(w,"hello...") //why this function block when multi request ? } func main() { fmt.Printf("server start working...\n") http.HandleFunc("/query",DoQuery) s := &http.Server{ Addr: ":9090",ReadTimeout: 30 * time.Second,WriteTimeout: 30 * time.Second,//MaxHeaderBytes: 1 << 20,} log.Fatal(s.ListenAndServe()) fmt.Printf("server stop...") }
我运行了你的代码,一切都按预期工作.我同时做了两个请求(卷曲localhost:9090 /查询),他们都在10秒后完成了.也许问题出在其他地方?这是我使用的命令:time curl -s localhost:9090 / query | echo $(curl -s localhost:9090 / query) – tjameson
thakns
真奇怪.
当我从chrome请求相同的url时,同时发送两个请求不处理,但是使用cur test可以同时处理.
但是当我发送两个请求使用不同的url时,它可以在同一时间处理.
[root @ localhost httpserver]#./ httppServer
服务器开始工作……
1374301640路径/查询?form = chrome2
1374301643路径/查询?form = chrome1
* 1374301715路径/查询?form = chrome
1374301725路径/查询?form = chrome *
是的,标准HTTP服务器将为每个请求启动一个新的goroutine.您应该能够并行执行数千个请求,具体取决于操作系统设置.
您的浏览器可能会限制它将向一台服务器发送的请求数量;确保您正在测试没有该限制/“优化”的客户端.
可靠的Go文档解释Http Server为每个请求创建一个新的gorotine:http://golang.org/pkg/net/http/#Server.Serve