# coding=utf-8
import redis
import threading
from redis import ConnectionPool
# https://blog.csdn.net/mixintu/article/details/102540460
# https://www.cnblogs.com/cnkai/p/7642787.html
# redis数据库连接池
class RedisPool(object):
_lock = threading.Lock( )
# 连接池连接(避免每次建立、释放连接的开销)
_pool = ConnectionPool(host = 'localhost', port = 6379, db = 2)
redis_pool = redis.Redis(connection_pool = _pool)
@classmethod # 连接redis实例
def instance(cls, *args, **kwargs):
if not hasattr(RedisPool, "_instance"):
with RedisPool._lock:
if not hasattr(RedisPool, "_instance"):
RedisPool._instance = RedisPool(*args, **kwargs)
return RedisPool._instance
# 键的操作
class RedisKey(object):
def __init__(self, redis_pool):
"""
ttl(key):获取key的过期时间,单位秒,-1为永久不过期
move(key, db):将key移动到其他数据库
flushall():删除所有数据库中的所有key
"""
self.redis_pool = redis_pool
# 键的类型
def type_key(self, key):
if self.redis_pool.exists(key):
self.redis_pool.type(key)
else:
print(f"{key}键:不存在")
# 返回键的数目
def count_key(self):
size = self.redis_pool.dbsize
redis的单例模式操作
最新推荐文章于 2024-06-21 13:33:15 发布