Redis如何知道它是否必须从数据库返回缓存的数据或新数据 [英] How would Redis get to know if it has to return cached data or fresh data from DB

查看:121
本文介绍了Redis如何知道它是否必须从数据库返回缓存的数据或新数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说,我正在使用数据库中的一些长期运行任务来抓取成千上万的内容或进行记录,并使用Redis对其进行缓存.第二天,有人更改了数据库中的几条记录.

Say, I'm Fechting thousands or record using some long runing task from DB and caching it using Redis. Next day somebody have changed few records in DB.

下次,redis如何知道它必须返回缓存的数据或再次必须重新访问DB中的所有数千条记录?

Next time how redis would know that it has to return cached data or again have to revisit that all thousands of record in DB?

这种同步是如何实现的?

How this synchronisation achived?

推荐答案

Redis不知道数据库中的数据是否已更新.

Redis has no idea whether the data in DB has been updated.

通常,我们使用Redis缓存数据,如下所示:

Normally, we use Redis to cache data as follows:

  1. 客户端检查数据,例如键值对,存在于Redis中.
  2. 如果密钥存在,则客户端从Redis获取相应的值.
  3. 否则,它将从数据库获取数据,并将其设置为Redis.客户端还为Redis中的键值对设置了到期时间,例如5分钟.
  4. 然后,Redis将为以后对同一密钥的所有请求提供服务.尽管Redis中的数据可能已过时.
  5. 但是,在5分钟后,此密钥将自动从Redis中删除.
  6. 转到步骤1.
  1. Client checks if the data, e.g. key-value pair, exists in Redis.
  2. If the key exists, client gets the corresponding value from Redis.
  3. Otherwise, it gets data from DB, and sets it to Redis. Also client sets an expiration, say 5 minutes, for the key-value pair in Redis.
  4. Then any subsequent requests for the same key will be served by Redis. Although the data in Redis might be out-of-date.
  5. However, after 5 minutes, this key will be removed from Redis automatically.
  6. Go to step 1.

因此,为了使您的数据保持Redis最新更新,您可以设置较短的到期时间.但是,您的数据库必须处理大量请求.

So in order to keep your data in Redis update-to-date, you can set a short expiration time. However, your DB has to serve lots of requests.

如果要大幅减少对数据库的请求,可以设置较大的到期时间.这样,Redis在大多数情况下都可以为请求提供可能的过期数据.

If you want to largely decrease requests to DB, you can set a large expiration time. So that, most of time, Redis can serve the requests with possible staled data.

您应该仔细考虑性能与陈旧数据之间的权衡.

这篇关于Redis如何知道它是否必须从数据库返回缓存的数据或新数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆