我有一个用go
编写的简单restapi。我使用python
request
库的不同进程多次测试调用它。但我遇到了requests.exceptions.ConnectionError
(下面是更详细的消息)。这让我很惊讶,因为我希望服务器能够处理并行请求。出于好奇,我在go
中实现了python
版本,但我无法重现错误!在
下面是我的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
来称呼它:
我用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
)会导致这个错误?我该怎么解决它?(我不知道我的问题是restapi还是如何使用requests
)。在
我的第二个问题是:为什么timer.go
工作正常?在
我正在使用:go 1.5
,python 2.7.6
,requests 2.2.1
,ubuntu 14.04
。在
目前没有回答
相关问题 更多 >
编程相关推荐