Python:密钥从REDIS中消失,过期无法正常工作

eqoofvh9  于 2023-01-20  发布在  Redis
关注(0)|答案(1)|浏览(92)

我正在CloudLinux/Litespeed服务器上运行Python Web应用程序。
Python版本:3.9.12 Redis版本:4.4.0
服务器具有大量RAM和硬件资源。
我的应用程序在REDIS中保存了许多密钥(1000/小时),几乎所有的都有过期。问题是,在检索密钥的时候,非常频繁地有些密钥已经不存在了,即使设置为只在180天后过期,而在其他情况下,一个应该在240秒后过期的密钥,它会在那里停留几个小时甚至几天。即使键没有设置过期,有时它也会消失。这个问题并不影响所有的键,但大约50%。似乎是一个间歇性的问题。
数据中心支持人员坚持认为问题不在REDIS上,因为有其他用户插入了同一个REDIS(听起来像是在混杂模式下运行),而且没有抱怨。
这是我的代码:

import redis      # redis 4.4.0

running_environment = 'SERVER'

if running_environment == 'SERVER' or running_environment == 'DEV':
    utils_cache_redis = redis.Redis(host='localhost', port=6379, db=0)



def set_value_at_redis_with_expiration(key_name, key_life_at_redis__seconds, key_value):
    if running_environment == 'SERVER' or running_environment == 'DEV':
        life_at_redis_days = key_life_at_redis__seconds / 60 / 60 / 24
        life_at_redis_days_formatted = ("%.2f" % life_at_redis_days)
        key_life_at_redis__seconds = int(key_life_at_redis__seconds)
        try:
            utils_cache_redis.set(key_name, str(key_value))
            utils_cache_redis.expire(key_name, key_life_at_redis__seconds)
            logger.debug(f'Set value at REDIS. Key name: [{key_name}]. Key life: [{life_at_redis_days_formatted} days] ({key_life_at_redis__seconds} seconds). Key value: [{key_value}]')
        except:
            logger.critical(f'Error while setting at REDIS. Variable name [{key_name}], Key life: [{life_at_redis_days_formatted} days] ({key_life_at_redis__seconds} seconds).  Variable value [{key_value}]')
    else:
        logger.info('Cannot set value at REDIS because it is not running at SERVER')





def check_if_key_is_present_at_redis(key):
    if running_environment == 'SERVER' or running_environment == 'DEV':
        try:
            if utils_cache_redis.exists(key) == True:
                logger.debug(f'Key found at REDIS: [{key}]')
                return True
            else:
                logger.debug(f'Key NOT found at REDIS: [{key}]')
                return False
        except:
            logger.critical(f'Error testing if key [{key}] exists at REDIS')
            return False
    else:
        logger.warning(f'Cannot check if key [{key}] is present at REDIS because is not running at server')
        return False


set_value_at_redis_with_expiration('key_name_at_redis', 10000000, 'this is a test')

if check_if_key_is_present_at_redis('key_name_at_redis') == True:
    print('Key found at redis')
else:
    print('Key not found at redis')

知道怎么修吗?

rsaldnfx

rsaldnfx1#

问题被发现了。密钥消失是因为REDIS运行在混杂模式下,多个用户可以访问同一个REDIS密钥池(在共享服务器中)。很可能有人在删除我的密钥。这个问题通过隔离REDIS来解决,防止其他人在REDIS上访问我的密钥。

相关问题