使用Gevent和WSGI阻止调用

Max*_*ank 3 wsgi blocking coroutine gevent

我刚刚开始使用协同程序,并阅读了gevent和greenlets.对于测试,我通过gevents pywsgi模块提供了此代码:

from gevent.pywsgi import WSGIServer
import gevent

def hello_world(env, start_response):
    gevent.sleep(5)
    start_response('200 OK', [('Content-Type', 'text/html')])
    return ["<b>hello world</b>"]

print 'Serving on 8088...'
WSGIServer(('127.0.0.1', 8888), hello_world).serve_forever()
Run Code Online (Sandbox Code Playgroud)

我期望一个结果,每个请求在显示文本之前会有5秒的延迟.然而,发生的是每个请求都通过调用gevent.sleep()排队等候,如果第二个请求在第一个请求之后立即启动,则会使第二个请求花费大约10秒.

serve_forever函数不是为每个请求生成新的greenlets吗?

pat*_*kcd 6

你用什么来提出要求?我怀疑那里存在问题.

我用ab(Apache Benchmark)测试了你的代码并得到了这个(输出编辑):

$ ab -c 200 -n 200 http://localhost:8888/

Completed 100 requests
Completed 200 requests
Finished 200 requests

Concurrency Level:      200
Time taken for tests:   5.048 seconds
Requests per second:    39.62 [#/sec] (mean)
Time per request:       5048.386 [ms] (mean)
Run Code Online (Sandbox Code Playgroud)

ab命令向gevent服务器发出200个并发请求.五秒钟后,所有请求都已完成.如果请求排队,正如您所建议的那样,此基准测试需要1000秒.

我想你的系统可能没有正确支持greenlet,但你用来测试的方法似乎更有可能阻止每个请求.即服务器支持并发,但客户端不支持并发.