关于redis主从复制模式下过期键的删除策略问题

最近在看《redis设计与实现》这本书时,看到redis过期键的删除部分,书中在讲主从复制模式下的过期键的删除时说道:从服务器不控制过期键的删除,只有主服务器删除一个过期键并显示的向从服务器发送一条del命令的时候,从服务器才会删除过期键,在这期间,即使从服务器在执行读命令,遇到过期键也不会将过期键删除。读到这里的时候我产生了一个疑问,想到如果一直以从服务器处理读请求,那岂不是永远无法触发主服务器发出del命令,过期键岂不是无法被删除,那过期时间的设置就没有了意义。
通过多方面查找资料,查看到redis官方文档(文档地址),文档中有这么一段话:

How Redis replication deals with expires on keys
Redis expires allow keys to have a limited time to live. Such a feature depends on the ability of an instance to count the time, however Redis slaves correctly replicate keys with expires, even when such keys are altered using Lua scripts.
To implement such a feature Redis cannot rely on the ability of the master and slave to have synchronized clocks, since this is a problem that cannot be solved and would result into race conditions and diverging data sets, so Redis uses three main techniques in order to make the replication of expired keys able to work:
1.Slaves don’t expire keys, instead they wait for masters to expire the keys. When a master expires a key (or evict it because of LRU), it synthesizes a DEL command which is transmitted to all the slaves.
2.However because of master-driven expire, sometimes slaves may still have in memory keys that are already logically expired, since the master was not able to provide the DEL command in time. In order to deal with that the slave uses its logical clock in order to report that a key does not exist only for read operations that don’t violate the consistency of the data set (as new commands from the master will arrive). In this way slaves avoid to report logically expired keys are still existing. In practical terms, an HTML fragments cache that uses slaves to scale will avoid returning items that are already older than the desired time to live.
3.During Lua scripts executions no keys expires are performed. As a Lua script runs, conceptually the time in the master is frozen, so that a given key will either exist or not for all the time the script runs. This prevents keys to expire in the middle of a script, and is needed in order to send the same script to the slave in a way that is guaranteed to have the same effects in the data set.
Once a slave is promoted to a master it will start to expire keys independently, and will not require any help from its old master.

这段话大致的意思就是讲redis如何处理过期键,
第1条大致翻译过来就是:从节点不会触发键过期,相反,从节点会等待主节点触发键过期。当主节点触发键过期时,主节点会同步一个del命令给所有的从节点。
第一条验证了书中所讲的结论:即由主服务器触发过期键事件,从服务器不控制过期键的删除。
我们的问题没有得到解决,来看第2条:然而由于主节点控制过期键的删除,所以有时从节点的内存中仍会存在实际上已经过期的键,这是因为主节点无法及时提供del命令导致的。为了应对这种情况,在读操作下,从节点使用其独有的逻辑时钟来标注一个键不存在,这并不会破坏数据一致性(主节点的命令早晚将会到达)。通过这种方式,从节点避免了返回一个已经过期的键。在实际经验中,一个通过从节点缓存去扩容的HTML页面缓存将可以避免没有按时过期的问题。
读到这里我们可以了解到,虽然从节点不会处理过期键,但是通过自己的逻辑控制,并不会返回已过期但是仍存在内存中的数据。
问题get✔️

评论 11
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值