我在go
编写了简单的REST API。我使用python
request
库使用不同的进程多次测试它。但是我遇到了requests.exceptions.ConnectionError
(下面有更详细的信息)。这对我来说是令人惊讶的,因为我希望服务器能够处理并行请求。出于好奇,我在python
中实现了go
版本,但我无法重现错误!
以下是我的REST API的代码:
package main
import (
"net/http"
"strconv"
"fmt"
)
func make_result(w http.ResponseWriter, r *http.Request) {
fmt.Println(r)
err := r.ParseForm()
if err != nil {
panic(err)
}
number_string := r.Form["Number"][0]
number, err := strconv.Atoi(number_string)
if err != nil {
panic(err)
}
fmt.Fprint(w, fmt.Sprint(number * 5))
}
我用python
,timer.py
:
import requests
from time import time
import random as rn
import sys
def time_get_requests(n_iterations):
start = time()
total = 0
for i in xrange(n_iterations):
if i % 1000 == 0:
print "processed: {} requests, time taken: {}".format(i, time() - start)
n = rn.randint(0, 1000)
temp = requests.get("http://localhost:8000/get_result", params={"Number": n})
total += int(temp.content)
print "Total: {}".format(total)
print "Total time: {}".format(time() - start)
if __name__ == "__main__":
time_get_requests(int(sys.argv[1]))
我正在使用go
,timer.go
:
package main
import(
"time"
"math/rand"
"strconv"
"log"
"os"
"github.com/parnurzeal/gorequest"
)
func main() {
rand.Seed( time.Now().UTC().UnixNano())
n_iterations, err := strconv.Atoi(os.Args[1])
if err != nil {
panic(err)
}
total := 0
start := time.Now()
request := gorequest.New()
for i := 0; i < n_iterations; i++ {
if i % 1000 == 0 {
log.Printf("%d: Time taken: %v\n", i, time.Now().Sub(start))
}
rand_int := rand.Intn(1000)
rand_int_str := strconv.Itoa(rand_int)
_, body, errs := request.
Get("http://localhost:8000/get_result").
Param("Number", rand_int_str).
End()
if len(errs) > 0 {
log.Fatalf("\033[0;31m%v\033[0m\n", errs)
}
int_body, err := strconv.Atoi(body)
if err != nil {
panic(err)
}
total += int_body
}
log.Printf("Total: %d\n", total)
total_time_taken := time.Now().Sub(start)
log.Printf("Total time: %v\n", total_time_taken)
}
我在我的linux shell中这样称呼它:
for i in {0..7}; do python timer.py 20000 & done
和
for i in {0..7}; do go run timer.go 20000 & done
(当我在一个处理器上运行时,两条线路运行良好)
我收到的错误消息:
resp = self.send(prep, **send_kwargs)
File "/usr/lib/python2.7/dist-packages/requests/sessions.py", line 558, in sen
d
raise ConnectionError(e)
requests.exceptions.ConnectionError: HTTPConnectionPool(host='localhost', port=8
000): Max retries exceeded with url: /get_result?Number=850 (Caused by <class 's
ocket.error'>: [Errno 99] Cannot assign requested address)
r = adapter.send(request, **kwargs)
File "/usr/lib/python2.7/dist-packages/requests/adapters.py", line 378, in send
我的主要问题:为什么我的python
部分(timer.py
)会导致此错误?我该怎么做才能解决这个问题? (我不知道我的问题是关于我的REST API还是我使用requests
的方式)。
我的第二个问题:为什么timer.go
能够正常运作?
我正在使用:go 1.5
,python 2.7.6
,requests 2.2.1
,ubuntu 14.04
。