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

查看:38
本文介绍了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 怎么知道它必须返回缓存数据还是必须再次访问数据库中的所有数千条记录?

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

这种同步是如何实现的?

How this synchronisation achived?

推荐答案

Redis不知道DB中的数据是否有更新.

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. 如果key存在,客户端从Redis获取对应的值.
  3. 否则,它会从 DB 获取数据,并将其设置为 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.

如果想大幅度减少对DB的请求,可以设置大的过期时间.这样,在大多数情况下,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天全站免登陆