为了实现 greenlet 节流,我曾经gevent.queue.Queue
实现一个令牌桶。
将模式变成函数装饰器:
from functools import wraps
from timeit import default_timer
import gevent
from gevent.queue import Queue
def gevent_throttle(calls_per_sec=0):
"""Decorates a Greenlet function for throttling."""
interval = 1. / calls_per_sec if calls_per_sec else 0
def decorate(func):
tq = Queue(1)
tq.put(0.)
@wraps(func)
def throttled_func(*args, **kwargs):
if calls_per_sec:
last, current = tq.get(), default_timer()
elapsed = current - last
if elapsed < interval:
gevent.sleep(interval - elapsed)
tq.put_nowait(default_timer())
return func(*args, **kwargs)
return throttled_func
return decorate
例子:
import requests
from gevent.pool import Pool
pool = Pool()
@gevent_throttle(10)
def worker(address):
"""Geocodes an address against Google Maps."""
print address
url='http://maps.googleapis.com/maps/api/geocode/json'
params = dict(address=address, sensor='false')
json = requests.get(url, params=params).json
return json
jobs = pool.imap(worker, 'NYC LA SF Chicago Boston Austin Portland'.split())
一个明显的缺点是工作人员以无序的方式从队列中抓取任务。然而,我想,大多数用例不需要在 worker greenlets 之间有任何特定的顺序。
您还看到其他缺点吗?有替代方案吗?