golang http server

吐血求助

先看下代码 很简单的一个golang http server

func hello (w http.ResponseWriter, r *http.Request) {
        fmt.Println("1",time.Now().Format("2006-01-02 15:04:05"))
        time.Sleep(5*time.Second)
        fmt.Println("2",time.Now().Format("2006-01-02 15:04:05"))
        w.Write([]byte("hello world"))
}
func main() {
http.HandleFunc("/hello",hello)
http.ListenAndServe(":8888", nil)
}

为了测试并发度,在响应函数中sleep 5s

go run 之后,client端使用ab模拟并发请求

ab -n 4 http://127.0.0.1:8888/hello

看server日志打印结果

localhost:src zhangjingpeng$ go run main.go
1 2016-01-05 22:08:05
2 2016-01-05 22:08:10
1 2016-01-05 22:08:10
2 2016-01-05 22:08:15
1 2016-01-05 22:08:15
2 2016-01-05 22:08:20
1 2016-01-05 22:08:20
2 2016-01-05 22:08:25

希望服务端是并发,即,首先都把1标签打印出来,然后再把2标签打印出来

看了net/http的源码,在1911行使用了go 去做并发。

1911                 go c.serve()

为什么在应用过程中不是并发的呢

阅读 6.4k
1 个回答

ab -c4 -n4 http://127.0.0.1:8888/hello

ab 没有并发,和 go 没有关系。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题