我正在尝试将gevent用作wsgi服务器,并使用tornado WSGIApplication来处理请求。这是代码
#!/usr/bin/env python
# coding=utf-8
import gevent
from gevent import monkey
monkey.patch_all(thread=False)
from gevent.pywsgi import WSGIServer
from tornado.wsgi import WSGIApplication
import tornado.web
import tornado.wsgi
import requests
class MainHandler(tornado.web.RequestHandler):
def get(self):
requests.get('http://google.com')
self.write('hello')
handlers = [
(r'/', MainHandler)
]
if __name__ == '__main__':
application = WSGIApplication(handlers)
server = WSGIServer(('', 9010), application)
server.serve_forever()
我使用apache基准来测试性能。测试命令是
ab -n 1000 -c 100 http://127.0.0.1:9010/
这导致每秒100req,它太慢了。在上面的代码中,我只是向另一方提出了一个http请求,我认为在这种情况下,gevent会在阻塞时切换到其他greenlet,它应该对性能影响不大,但gevent的性能从每秒1600req降低到100每秒req,我无法弄清楚原因。
有人能解释一下吗?
答案 0 :(得分:2)
您好问题是您没有产生实际的greenlet,而且tornado.web.ascynhronous装饰器不支持WSGI服务器。
但主要的逻辑工作,我能够使用HTTP服务器(我不知道你是否绑定到WSGI服务器,但我想不是因为你可以只是反向代理)
我发现很多人都想在龙卷风中使用gevent,包括我(我们在FriendCode使用龙卷风和gevent),所以我写了这个:
# Gevent monkeypath
from gevent import monkey
monkey.patch_all()
# Gevent imports
import gevent
# Python immports
import functools
# Tornado imports
import tornado.ioloop
import tornado.web
import tornado.httpserver
# Request imports
import requests
# Asynchronous gevent decorator
def gasync(func):
@tornado.web.asynchronous
@functools.wraps(func)
def f(self, *args, **kwargs):
#self._auto_finish = False
return gevent.spawn(func, self, *args, **kwargs)
return f
# Constants
URL_TO_FETCH = 'http://google.co.uk/'
# Global
I = 0
class MainHandler(tornado.web.RequestHandler):
@gasync
def get(self):
global I
r = requests.get(URL_TO_FETCH)
I += 1
print('Got page %d (length=%d)' % (I, len(r.content)))
self.write("Done")
self.finish()
# Our URL Mappings
handlers = [
(r"/", MainHandler),
]
def main():
# Setup app and HTTP server
application = tornado.web.Application(handlers)
http_server = tornado.httpserver.HTTPServer(application)
http_server.listen(9998)
# Start ioloop
tornado.ioloop.IOLoop.instance().start()
if __name__ == "__main__":
main()
在这个示例中有两个关键部分,你正确的猴子修补部分,然后是我写的 gasync 装饰器,它所做的就是设置一个异步的方法(通过龙卷风的术语) ,这意味着该方法必须自己调用self.finish()来将响应发送到客户端,因为龙卷风在请求同步时自动调用它,但它不是你想要的异步)。
我希望有帮助,代码在这里运行良好我已经测试过:
$ ab -n 100 -c 100 http://localhost:9998/
给出了:
This is ApacheBench, Version 2.3 <$Revision: 655654 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/
Benchmarking localhost (be patient).....done
Server Software: TornadoServer/2.3
Server Hostname: localhost
Server Port: 9998
Document Path: /
Document Length: 4 bytes
Concurrency Level: 100
Time taken for tests: 0.754 seconds
Complete requests: 100
Failed requests: 0
Write errors: 0
Total transferred: 15900 bytes
HTML transferred: 400 bytes
Requests per second: 132.67 [#/sec] (mean)
Time per request: 753.773 [ms] (mean)
Time per request: 7.538 [ms] (mean, across all concurrent requests)
Transfer rate: 20.60 [Kbytes/sec] received
Connection Times (ms)
min mean[+/-sd] median max
Connect: 2 4 0.8 4 5
Processing: 379 572 104.4 593 748
Waiting: 379 572 104.4 593 748
Total: 383 576 104.3 596 752
Percentage of the requests served within a certain time (ms)
50% 596
66% 640
75% 672
80% 679
90% 707
95% 722
98% 735
99% 752
100% 752 (longest request)
正如您所看到的,总时间大致等于最长请求的时间,请记住异步时:
total_time = max(all_individual_times) + n*some_overhead
n 是请求数, some_overhead 是一个不变的开销。
希望有所帮助:)
答案 1 :(得分:2)
我有同样的需求,但我正在使用期货和gen.coroutine,所以我不得不稍微修改它以便与我的代码兼容,如果其他人也需要它我会把它放在这里:
#
# encoding: utf-8
from gevent import monkey
monkey.patch_all()
# Gevent imports
import gevent
# Python immports
import functools
# Tornado imports
import tornado.ioloop
import tornado.web
import tornado.gen
import tornado.httpserver
# Request imports
import requests
from tornado.concurrent import Future
# Asynchronous gevent decorator
def gfuture(func):
@functools.wraps(func)
def f(*args, **kwargs):
loop = tornado.ioloop.IOLoop.current()
future = Future()
def call_method():
try:
result = func(*args, **kwargs)
loop.add_callback(functools.partial(future.set_result, result))
except Exception, e:
loop.add_callback(functools.partial(future.set_exception, e))
gevent.spawn(call_method)
return future
return f
# Constants
URL_TO_FETCH = 'http://google.com/'
# Global
I = 0
@gfuture
def gfetch(url, i):
r = requests.get(url)
return i
class MainHandler(tornado.web.RequestHandler):
@tornado.web.asynchronous
@tornado.gen.coroutine
def get(self):
global I
I += 1
n = I
print "=> %s" % n
n = yield gfetch(URL_TO_FETCH, n)
print "<= %s" % n
self.write("Done %s" % n)
# Our URL Mappings
handlers = [(r"/", MainHandler)]
def main():
# Setup app and HTTP server
application = tornado.web.Application(handlers)
http_server = tornado.httpserver.HTTPServer(application)
http_server.listen(9998)
# Start ioloop
tornado.ioloop.IOLoop.instance().start()
if __name__ == "__main__":
main()
答案 2 :(得分:0)
尝试仅使用gevent示例应用程序测试requests
包,如果它是真正的异步,则chceck。也许原因是gevent无法正确修补requests
但我认为您的解决方案与gevent站点不同步:您正在尝试运行2个事件循环。我想你现在的过程看起来如下:
get
方法,该方法运行gevent事件循环(gevent在专用greenlet中隐式启动事件循环)答案 3 :(得分:0)
Tornado(Twisted)和gevent做同样的事情,为了获得最佳效果,你应该保持在相同的技术堆栈中,而不是混合两者。要么使用WSGI Web框架,要么像瓶子或瓶子一样使用gevent,要么使用扭曲和龙卷风。