为什么在此gevent程序中仅与Redis建立了一个连接? [英] Why only one connection to redis was made in this gevent program?

查看:96
本文介绍了为什么在此gevent程序中仅与Redis建立了一个连接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用gevent来构建服务器,该服务器执行一些redis任务并将结果返回给客户端.但是性能很差.经过一番研究,我发现与Redis仅存在一种连接.看起来只有一个绿色的小精灵.这是我的程序:

I'm using gevent to build a server which do some redis stuff and return the result to client. But the performance is bad. After some research I found that there is only one connection to redis. It looks like there is only one greenlet spawned. Here is my program:

#!/usr/bin/env python
from gevent import monkey
monkey.patch_all()
import gevent
from gevent.wsgi import WSGIServer
from gevent.pool import Pool
import gevent.socket
from cgi import parse_qs, escape
import json
import redis

p = redis.ConnectionPool()

def app(environ, start_response):
    status = '200 OK'
    body = ''

    path = environ.get('PATH_INFO', '').lstrip('/')
    parameters = parse_qs(environ.get('QUERY_STRING', ''))

    r = redis.Redis(connection_pool=p)
    if path == 'top':
        l = r.zrevrange('online', 0, 50, True)
        body = json.dumps({'onlinetime':map(lambda (pid, online): {'pid':pid, 'onlinetime':online}, l)}) + '\n'

    headers = [
        ('Content-Type', 'text/html'),
        ('Content-Length', str(len(body))),
    ]

    print 'in_use_conn:', len(p._in_use_connections), 'created_connections:', p._created_connections
    start_response(status, headers)

    yield body

def main():
    pool = Pool(1000)
    WSGIServer(('', 7332), app, spawn=pool, log=None).serve_forever()

if __name__ == '__main__':
    main()

我的程序有问题吗?为什么只有一个与Redis的连接?

Is there something wrong with my program? Why there is only one connection to redis?

推荐答案

看看我不是100%是您的猴子补丁正在解决这个问题,但我将其替换为:

I'm not 100% is your monkey-patching is doing the trick but I'd replace it with:

import gevent
import redis.connection
redis.connection.socket = gevent.socket

您还可以使用受gevent支持的Redis连接来创建自己的池...

You could also go and create your own pool with gevent supported connection to redis...

这篇关于为什么在此gevent程序中仅与Redis建立了一个连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆