简体   繁体   English

Redis 缓存过期比设置的过期时间快很多

[英]Redis cache expires lot faster than the set expiry time

When trying to read from the cache using the python Redis package, it shows as expired.尝试使用 python Redis 包从缓存中读取时,它显示为已过期。 This happens within 5 seconds of setting the cache.这会在设置缓存后 5 秒内发生。 Any reads within the 5 seconds work though.不过,5 秒内的任何读取都有效。

But the key is set to expire in 180 seconds or 3 minutes.但是密钥设置为在 180 秒或 3 分钟后过期。 Is this even remotely possible.这甚至可能是远程的。 Also the redis key is not written to / invalidated anytime after the first write.此外,在第一次写入后,redis 密钥不会随时写入/失效。

import redis
time_to_expire_s=180
client = redis.StrictRedis(host=self.host, port=self.port, password=self.password)
client.set(key, zlib.compress(value.encode('utf-8')), ex=time_to_expire_s)

Is this weird behavior.这是奇怪的行为吗。 Setting to a longer cache like 3600 (1hr) solves my issue, but wanted to know why a 3-minute cache would expire in 5 seconds...设置为 3600(1 小时)等更长的缓存解决了我的问题,但想知道为什么 3 分钟的缓存会在 5 秒后过期...

Thank you谢谢

I'd definitely point to the Redis server you are running, it might be misconfigured, I'm giving you a fully working example below, which uses docker and keeps the cache for 3 minutes (or whatever time you want):我肯定会指出您正在运行的 Redis 服务器,它可能配置错误,我在下面为您提供了一个完整的示例,它使用 docker 并将缓存保留 3 分钟(或您想要的任何时间):

Firstly, assuming you have docker installed:首先,假设你已经安装了 docker:

docker pull redis

Secondly run your container and exposes the port 6379其次运行你的容器并暴露端口 6379

docker run -d -p 6379:6379 redis:latest

And here it goes the Python code which works perfectly by keeping the cache for 180 seconds:这里是 Python 代码,它通过将缓存保持 180 秒而完美运行:

from redis.client import Redis
import random
import zlib

class Cache:
   def __init__(self):
      self.time_to_expire_s=180
      self.client = Redis(host="localhost", port=6379)
   def set_key(self, key, value):
      self.client.set(key, zlib.compress(value.encode('utf-8')), ex=self.time_to_expire_s)
   def get_key(self, key):
      return self.client.get(key)

if __name__ == "__main__":
   cache = Cache()
   rnd = random.Random()
   rnd_num=  rnd.randint(1,100)
   print(f"rdn {rnd_num}")
   if cache.get_key("MyCacheKey") is None:
      cache.set_key("MyCacheKey", "Myvalue"+str(rnd_num))
   else:
      print(zlib.decompress(cache.get_key("MyCacheKey")))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM