我正在执行多个 API 调用,但在每个 API 调用中,我都在检查 redis 连接是否可用。仅显示以下 API 调用之一。
def check_redis_conn():
redis_exists = RedisCache.is_redis_available()
if redis_exists is True:
set_Data = RedisCache.set_data("message", "This is redis Test")
return True
else:
return redis_exists
def hello_vortex(request):
is_redis_connected = check_redis_conn()
if is_redis_connected is True:
data = {'Description': 'This is the sample API call', 'version': 1.0}
return JsonResponse{data,safe=False}
else:
return is_redis_connected
RedisCache 类:
@classmethod
def set_connect(cls):
try:
redis_instance = redis.StrictRedis(
host='127.0.0.1',
port=6379,
)
@classmethod
def get_conn(cls):
try:
cls.redis_instance = cls.set_connect()
return cls.redis_instance
except Exception as e:
return JsonResponse{'message':'Error while connecting', safe=False}
@classmethod
def is_redis_available(cls):
try:
isConn = cls.get_conn()
isConn.ping()
return True
except Exception as e:
return JsonResponse{'message':'Error while connecting', safe=False}
如何在服务器启动时仅检查一次 redis 连接,如果连接不可用,则在服务器上返回 Json 响应。