RODY/app/utils/redis_config.py
552068321@qq.com 6f7de660aa first commit
2022-11-04 17:37:08 +08:00

67 lines
1.7 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""
redis 配置类
"""
import sys
import redis
from ..configs import default
class RedisCli(object):
def __init__(self, *, host: str, port: str, password: str, db: int, socket_timeout=5):
# redis对象在 @app.on_event('startup') 中连接创建
self._redis_client = None
self.host = host
self.port = port
self.password = password
self.db = db
self.socket_timeout = socket_timeout
def init_redis_connect(self) -> None:
"""
初始化链接
:return:
"""
try:
r = redis.ConnectionPool(
host=self.host,
port=self.port,
password=self.password,
db=self.db,
socket_timeout=self.socket_timeout,
decode_responses=True # 解码
)
self._redis_client = redis.StrictRedis(connection_pool=r)
if not self._redis_client.ping():
print('连接超时')
sys.exit()
except (redis.AuthenticationError, Exception) as e:
print('连接redis异常')
sys.exit()
def get_redis(self):
return self._redis_client
# 使实例化后的对象赋予redis对象的方法和属性
def __getattr__(self, item):
return self._redis_client.has_key(item)
def __getitem__(self, item):
return self._redis_client[item]
def __setitem__(self, key, value):
self._redis_client[key] = value
def __delitem__(self, key):
del self._redis_client[key]
redis_client = RedisCli(
host=default.db['host'],
port=default.db['port'],
password=default.db['password'],
db=default.db['db'],
)