【问题标题】:Why using Gunicorn with GEvent could increate the query time to Redis/Database?为什么使用 Gunicorn 和 GEvent 会增加对 Redis/数据库的查询时间?
【发布时间】:2019-10-14 10:53:17
【问题描述】:

在具有 Redis 服务器 (v4.x) 的实际生产负载(Web 应用程序)中,当使用带有 worker_class gevent 的 gunicorn 时,查询时间增加了 3。数据库访问也变得更糟(但不是那么多,只有 50%) .我试图弄清楚为什么会发生这种情况。有任何想法吗?该应用非常 IO Bound,每个请求都有大量的数据库查询和 redis 访问,这应该是 gevent 的完美场景。

从 SYNC 转移到 GEVENT(~11 A.M)

猴子修补套接字会以某种方式降低性能吗?我尝试微调worker_connections,但没有成功,即使只有 2 的极低级别(几乎再次同步),也会给我同样糟糕的结果。我是否错过了gevent 和它的伪线程如何工作的一些问题?

免责声明:我正在使用 NewRelic 来监控性能和 redis-py/django/mysql。我尝试了一些调整,比如为 Redis 使用 BlockingConnectionPool,但我的数据库访问性能也下降了,所以 Redis 不是唯一的问题。工作人员大小为 5(CPU * 2 + 1)。我也有大量的 GreenletExit/ConnectionError[redis] 在随机时间,通过将 worker_connections 从 2k(默认)移动到 10 来最小化。

【问题讨论】:

  • 一些代码会对我们有很大帮助。
  • 我没有要分享的特定代码部分。想象一个 Django 应用程序,具有一些缓存访问(可能 5 次或更多调用)、更多数据库访问(30 多次调用)、中间件和往常一样。 “常见的网络东西”。
  • 更多关于如何实例化 redis 连接池。我将 redis 与 gevent 一起使用,我的表现非常出色。但是我不得不意识到redis创建了一个连接池。

标签: python django redis gunicorn gevent


【解决方案1】:

monkeypatching 后的 redis 连接示例。

_rconn = None
def redisconn():
    global _rconn
    if _rconn is None:
        try:
            _rconn = redis.StrictRedis(host=redisconfig['host'], port=redisconfig['port'], db=redisconfig['db'])
        except:
            traceback.print_exc()
            _rconn = None
    return _rconn

class RedisCache(object):
    def __init__(self):
        #in case of a lost connection lets sit and wait till it's online
        global _rconn
        if not _rconn:
            while not _rconn:
                try:
                    redisconn()
                except:
                    print('Attempting Connection To Redis...')
                    gsleep(1)
        self.r = _rconn
        self.rpool = self.r.connection_pool

    def get(self, key):
        return self.r.get(key)

    def set(self, key, meta, expire=86400, nx=True):
        return self.r.set(key, json.loads(meta), ex=expire, nx=nx)

    def connections(self):
        return self.rpool._created_connections

    def inuse(self):
        return self.rpool._in_use_connections

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-09-24
    • 2013-09-29
    • 1970-01-01
    • 1970-01-01
    • 2019-08-11
    • 2012-02-02
    • 1970-01-01
    相关资源
    最近更新 更多