每天进步一点点-构建redis连接池

import threading

import redis
from rediscluster import StrictRedisCluster

from configs import CURRENT_CONFIG


# 单连
class RedisPoolUtil(object):
    """
    多个redis实例共享同一个连接池
    """
    _instance_lock = threading.Lock()

    def __init__(self):
        if not hasattr(RedisPoolUtil, 'pool'):
            RedisPoolUtil.create_pool()
        self.conn = redis.Redis(connection_pool=RedisPoolUtil.pool)

    def __new__(cls, *args, **kwargs):
        if not hasattr(RedisPoolUtil, '_instance'):
            with RedisPoolUtil._instance_lock:
                if not hasattr(RedisPoolUtil, '_instance'):
                    RedisPoolUtil._instance = object.__new__(cls)
        return RedisPoolUtil._instance

    @classmethod
    def create_pool(cls):
        RedisPoolUtil.pool = redis.ConnectionPool(
            host=CURRENT_CONFIG.get("REDIS_SERVER_HOST") if CURRENT_CONFIG.get(
                "REDIS_SERVER_HOST") else "localhost",
            port=CURRENT_CONFIG.get("REDIS_SERVER_PORT") if CURRENT_CONFIG.get(
                "REDIS_SERVER_PORT") else 6379,
            password=CURRENT_CONFIG.get("REDIS_SERVER_PWD") if CURRENT_CONFIG.get(
                "REDIS_SERVER_PWD") else None,
            db=CURRENT_CONFIG.get('REDIS_SERVER_DB') if CURRENT_CONFIG.get('REDIS_SERVER_DB') else 0,
            max_connections=100,

        )


# 集群
class RedisCluster(object):
    """
    redis集群连接
    """

    def __init__(self, conn_list=None, password=None):
        """
        :param conn_list: 集群节点host
        :param password: 集群连接密码
        """
        self.conn_list = conn_list
        self.password = password

    def connect(self):
        """
        连接redis集群
        :return: conn,err
        """

        try:
            # 非密码连接redis集群
            # redis_conn = StrictRedisCluster(startup_nodes=self.conn_list)
            # 使用密码连接redis集群
            redis_conn = StrictRedisCluster(startup_nodes=self.conn_list,
                                            password=self.password,
                                            decode_responses=True,
                                            skip_full_coverage_check=True)
            return redis_conn, None
        except Exception as e:
            err = "连接redis集群失败,错误信息:%s" % e
            return False, err
posted @ 2022-09-14 10:17  Alive_2020  阅读(135)  评论(0编辑  收藏  举报