为什么我的golang服务器不处理并发请求?

这个简单的HTTP服务器包含对time.Sleep()的调用,使每个请求花费五秒钟。 当我尝试在浏览器中快速加载多个选项卡时,显然每个请求都是按顺序排队和处理的。 我怎样才能使它处理并发请求?

package main import ( "fmt" "net/http" "time" ) func serve(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, "Hello, world.") time.Sleep(5 * time.Second) } func main() { http.HandleFunc("/", serve) http.ListenAndServe(":1234", nil) } 

实际上,在写完这个问题之后,我才find了答案,这很微妙。 无论如何,我都会发布,因为我无法在Google上find答案。 你能看到我做错了吗?

您的程序已经同时处理这些请求。 您可以使用ab (Apache 2附带的基准testing工具)对其进行testing:

 ab -c 500 -n 500 http://localhost:1234/ 

在我的系统中,基准testing共需要5043ms来处理所有500个并发请求。 这只是你的浏览器,它限制了每个网站的连接数量。

Benchmarking Go程序并不是那么容易,因为您需要确保您的基准testing工具不是瓶颈,而且它也能够处理多个并发连接。 因此,使用一对专用计算机来产生负载是个好主意。

在Server.go中,当连接被接受时,在例行服务function中产生去程序。 以下是摘录:

 // Serve accepts incoming connections on the Listener l, creating a // new service goroutine for each. The service goroutines read requests and // then call srv.Handler to reply to them. func (srv *Server) Serve(l net.Listener) error { for { rw, e := l.Accept() if e != nil { ...... c, err := srv.newConn(rw) if err != nil { continue } c.setState(c.rwc, StateNew) // before Serve can return go c.serve() } } 

如果您使用xhr请求,请确保xhr实例是一个局部variables。

例如, xhr = new XMLHttpRequest()是一个全局variables。 当你使用相同的xhrvariables进行并行请求时,只会收到一个结果。 所以,你必须像这样在本地声明xhr var xhr = new XMLHttpRequest()