V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
BeginMan
V2EX  ›  Redis

redis 连接做成单例好么?

  •  
  •   BeginMan · 2015-07-27 17:21:32 +08:00 · 7417 次点击
    这是一个创建于 3188 天前的主题,其中的信息可能已经有所发展或是发生改变。

    对于redis连接我的处理有两个方案:

    1. 每次请求创建一个新的连接(设置redis timeout)
    2. redis单例作用于每次请求,共用一个连接池

    个人觉得第二种可以减少对象创建,销毁的开销,减少redis连接数,但是对于高并发情况下是否不尽人意,或者说对于redis在设置了连接超市的情况下,使用redis单例是否有意义?

    7 条回复    2015-07-27 18:41:09 +08:00
    BeginMan
        1
    BeginMan  
    OP
       2015-07-27 17:22:16 +08:00
    求指导 :-D
    ipconfiger
        2
    ipconfiger  
       2015-07-27 17:26:05 +08:00
    有现成的连接池不用!
    BeginMan
        3
    BeginMan  
    OP
       2015-07-27 17:33:37 +08:00
    我现在的处理如下:

    class RedisSinglePool(object):
    """redis单例"""
    def __init__(self, db=0):
    self.db = db
    if not hasattr(RedisSinglePool, 'pool'):
    RedisSinglePool.createPool(self.db)
    self._connection = redis.Redis(connection_pool=RedisSinglePool.pool)

    @staticmethod
    def createPool(db):
    # 创建连接池
    RedisSinglePool.pool = redis.ConnectionPool(
    host=settings.redis_svr_addr,
    port=settings.redis_svr_addr_port,
    db=db,
    password=settings.redis_svr_pass)

    def getR(self):
    return self._connection

    维护一个连接池。
    vincenttone
        4
    vincenttone  
       2015-07-27 17:37:06 +08:00
    要看扩展是不是有连接池
    aisk
        5
    aisk  
       2015-07-27 17:53:38 +08:00
    没明白你的代码要干嘛,直接全局创建 redis 实例然后 import 不就好了?
    lakechan96
        6
    lakechan96  
       2015-07-27 17:54:01 +08:00
    见过一个项目的redis把最大连接数设置到了100万个,也许是下下策,慎用
    BeginMan
        7
    BeginMan  
    OP
       2015-07-27 18:41:09 +08:00
    @aisk 恩恩,我有点小题大做了
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5662 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 02:06 · PVG 10:06 · LAX 19:06 · JFK 22:06
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.