Redis 工具类
实现的功能包括 redis 读取队列数据,存储和读取 hash 数据,Redis 的创建,RedisCluster 的创建
import sys
import redis
from rediscluster import RedisCluster
is_redis_cluster = True
class RedisObj(object):
def __init__(self):
self.save_time = 6048800
self.conn = redis.ConnectionPool(host=host, port=port, password=password)
if is_redis_cluster:
self.__db = self.init_redis_cluster()
else:
self.__db = redis.Redis(connection_pool=self.conn)
self.key = None
def init_redis_cluster(self):
startup_nodes = [
{'host': '10.70.130.153', 'port': 6379},
{'host': '10.80.140.154', 'port': 6379},
{'host': '10.90.150.155', 'port': 6379}
]
try:
conn = RedisCluster(startup_nodes=startup_nodes,
decode_responses=False,
skip_full_coverage_check=True,
password='123456',
max_connections=100)
return conn
except Exception as e:
print("connect error ", str(e))
sys.exit(1)
# 存储数据 hash 格式 save_time: 保存时间
def set(self, key, value):
self.__db.set(key, value, self.save_time)
# 获取数据
def get(self, name):
item = self.__db.get(name)
return item
def set_name(self, name):
self.key = name
# 一次取一条队列数据
def pop(self, item):
self.__db.lpop(self.key)
# 批量取队列数据
def get_data_list(self):
item = self.__db.lrange(self.key, 0, -1)
return item
# 批量删除队列
def del_data_list(self, item):
if item:
self.__db.ltrim(self.key, item, -1)
return item
网友评论