经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 数据库/运维 » Redis » 查看文章
Redis中LFU算法的深入分析
来源:jb51  时间:2019/6/3 8:38:21  对本文有异议

前言

Redis中的LRU算法文中说到,LRU有一个缺陷,在如下情况下:

~~~~~A~~~~~A~~~~~A~~~~A~~~~~A~~~~~A~~|
~~B~~B~~B~~B~~B~~B~~B~~B~~B~~B~~B~~B~|
~~~~~~~~~~C~~~~~~~~~C~~~~~~~~~C~~~~~~|
~~~~~D~~~~~~~~~~D~~~~~~~~~D~~~~~~~~~D|

会将数据D误认为将来最有可能被访问到的数据。

Redis作者曾想改进LRU算法,但发现Redis的LRU算法受制于随机采样数maxmemory_samples,在maxmemory_samples等于10的情况下已经很接近于理想的LRU算法性能,也就是说,LRU算法本身已经很难再进一步了。

于是,将思路回到原点,淘汰算法的本意是保留那些将来最有可能被再次访问的数据,而LRU算法只是预测最近被访问的数据将来最有可能被访问到。我们可以转变思路,采用一种LFU(Least Frequently Used)算法,也就是最频繁被访问的数据将来最有可能被访问到。在上面的情况中,根据访问频繁情况,可以确定保留优先级:B>A>C=D。

Redis中的LFU思路

在LFU算法中,可以为每个key维护一个计数器。每次key被访问的时候,计数器增大。计数器越大,可以约等于访问越频繁。

上述简单算法存在两个问题:

  • 在LRU算法中可以维护一个双向链表,然后简单的把被访问的节点移至链表开头,但在LFU中是不可行的,节点要严格按照计数器进行排序,新增节点或者更新节点位置时,时间复杂度可能达到O(N)。
  • 只是简单的增加计数器的方法并不完美。访问模式是会频繁变化的,一段时间内频繁访问的key一段时间之后可能会很少被访问到,只增加计数器并不能体现这种趋势。

第一个问题很好解决,可以借鉴LRU实现的经验,维护一个待淘汰key的pool。第二个问题的解决办法是,记录key最后一个被访问的时间,然后随着时间推移,降低计数器。

Redis对象的结构如下:

  1. typedef struct redisObject {
  2. unsigned type:4;
  3. unsigned encoding:4;
  4. unsigned lru:LRU_BITS; /* LRU time (relative to global lru_clock) or
  5. * LFU data (least significant 8 bits frequency
  6. * and most significant 16 bits access time). */
  7. int refcount;
  8. void *ptr;
  9. } robj;

在LRU算法中,24 bits的lru是用来记录LRU time的,在LFU中也可以使用这个字段,不过是分成16 bits与8 bits使用:

  1. 16 bits 8 bits
  2. +----------------+--------+
  3. + Last decr time | LOG_C |
  4. +----------------+--------+

高16 bits用来记录最近一次计数器降低的时间ldt,单位是分钟,低8 bits记录计数器数值counter。

LFU配置

Redis4.0之后为maxmemory_policy淘汰策略添加了两个LFU模式:

  • volatile-lfu:对有过期时间的key采用LFU淘汰算法
  • allkeys-lfu:对全部key采用LFU淘汰算法

还有2个配置可以调整LFU算法:

  1. lfu-log-factor 10
  2. lfu-decay-time 1

lfu-log-factor可以调整计数器counter的增长速度,lfu-log-factor越大,counter增长的越慢。

lfu-decay-time是一个以分钟为单位的数值,可以调整counter的减少速度

源码实现

在lookupKey中:

  1. robj *lookupKey(redisDb *db, robj *key, int flags) {
  2. dictEntry *de = dictFind(db->dict,key->ptr);
  3. if (de) {
  4. robj *val = dictGetVal(de);
  5.  
  6. /* Update the access time for the ageing algorithm.
  7. * Don't do it if we have a saving child, as this will trigger
  8. * a copy on write madness. */
  9. if (server.rdb_child_pid == -1 &&
  10. server.aof_child_pid == -1 &&
  11. !(flags & LOOKUP_NOTOUCH))
  12. {
  13. if (server.maxmemory_policy & MAXMEMORY_FLAG_LFU) {
  14. updateLFU(val);
  15. } else {
  16. val->lru = LRU_CLOCK();
  17. }
  18. }
  19. return val;
  20. } else {
  21. return NULL;
  22. }
  23. }

当采用LFU策略时,updateLFU更新lru:

  1. /* Update LFU when an object is accessed.
  2. * Firstly, decrement the counter if the decrement time is reached.
  3. * Then logarithmically increment the counter, and update the access time. */
  4. void updateLFU(robj *val) {
  5. unsigned long counter = LFUDecrAndReturn(val);
  6. counter = LFULogIncr(counter);
  7. val->lru = (LFUGetTimeInMinutes()<<8) | counter;
  8. }

降低LFUDecrAndReturn

首先,LFUDecrAndReturn对counter进行减少操作:

  1. /* If the object decrement time is reached decrement the LFU counter but
  2. * do not update LFU fields of the object, we update the access time
  3. * and counter in an explicit way when the object is really accessed.
  4. * And we will times halve the counter according to the times of
  5. * elapsed time than server.lfu_decay_time.
  6. * Return the object frequency counter.
  7. *
  8. * This function is used in order to scan the dataset for the best object
  9. * to fit: as we check for the candidate, we incrementally decrement the
  10. * counter of the scanned objects if needed. */
  11. unsigned long LFUDecrAndReturn(robj *o) {
  12. unsigned long ldt = o->lru >> 8;
  13. unsigned long counter = o->lru & 255;
  14. unsigned long num_periods = server.lfu_decay_time ? LFUTimeElapsed(ldt) / server.lfu_decay_time : 0;
  15. if (num_periods)
  16. counter = (num_periods > counter) ? 0 : counter - num_periods;
  17. return counter;
  18. }

函数首先取得高16 bits的最近降低时间ldt与低8 bits的计数器counter,然后根据配置的lfu_decay_time计算应该降低多少。

LFUTimeElapsed用来计算当前时间与ldt的差值:

  1. /* Return the current time in minutes, just taking the least significant
  2. * 16 bits. The returned time is suitable to be stored as LDT (last decrement
  3. * time) for the LFU implementation. */
  4. unsigned long LFUGetTimeInMinutes(void) {
  5. return (server.unixtime/60) & 65535;
  6. }
  7.  
  8. /* Given an object last access time, compute the minimum number of minutes
  9. * that elapsed since the last access. Handle overflow (ldt greater than
  10. * the current 16 bits minutes time) considering the time as wrapping
  11. * exactly once. */
  12. unsigned long LFUTimeElapsed(unsigned long ldt) {
  13. unsigned long now = LFUGetTimeInMinutes();
  14. if (now >= ldt) return now-ldt;
  15. return 65535-ldt+now;
  16. }

具体是当前时间转化成分钟数后取低16 bits,然后计算与ldt的差值now-ldt。当ldt > now时,默认为过了一个周期(16 bits,最大65535),取值65535-ldt+now。

然后用差值与配置lfu_decay_time相除,LFUTimeElapsed(ldt) / server.lfu_decay_time,已过去n个lfu_decay_time,则将counter减少n,counter - num_periods。

增长LFULogIncr

增长函数LFULogIncr如下:

  1. /* Logarithmically increment a counter. The greater is the current counter value
  2. * the less likely is that it gets really implemented. Saturate it at 255. */
  3. uint8_t LFULogIncr(uint8_t counter) {
  4. if (counter == 255) return 255;
  5. double r = (double)rand()/RAND_MAX;
  6. double baseval = counter - LFU_INIT_VAL;
  7. if (baseval < 0) baseval = 0;
  8. double p = 1.0/(baseval*server.lfu_log_factor+1);
  9. if (r < p) counter++;
  10. return counter;
  11. }

counter并不是简单的访问一次就+1,而是采用了一个0-1之间的p因子控制增长。counter最大值为255。取一个0-1之间的随机数r与p比较,当r<p时,才增加counter,这和比特币中控制产出的策略类似。p取决于当前counter值与lfu_log_factor因子,counter值与lfu_log_factor因子越大,p越小,r<p的概率也越小,counter增长的概率也就越小。增长情况如下:

+--------+------------+------------+------------+------------+------------+
| factor | 100 hits   | 1000 hits  | 100K hits  | 1M hits    | 10M hits   |
+--------+------------+------------+------------+------------+------------+
| 0      | 104        | 255        | 255        | 255        | 255        |
+--------+------------+------------+------------+------------+------------+
| 1      | 18         | 49         | 255        | 255        | 255        |
+--------+------------+------------+------------+------------+------------+
| 10     | 10         | 18         | 142        | 255        | 255        |
+--------+------------+------------+------------+------------+------------+
| 100    | 8          | 11         | 49         | 143        | 255        |
+--------+------------+------------+------------+------------+------------+

可见counter增长与访问次数呈现对数增长的趋势,随着访问次数越来越大,counter增长的越来越慢。

新生key策略

另外一个问题是,当创建新对象的时候,对象的counter如果为0,很容易就会被淘汰掉,还需要为新生key设置一个初始counter,createObject:

  1. robj *createObject(int type, void *ptr) {
  2. robj *o = zmalloc(sizeof(*o));
  3. o->type = type;
  4. o->encoding = OBJ_ENCODING_RAW;
  5. o->ptr = ptr;
  6. o->refcount = 1;
  7.  
  8. /* Set the LRU to the current lruclock (minutes resolution), or
  9. * alternatively the LFU counter. */
  10. if (server.maxmemory_policy & MAXMEMORY_FLAG_LFU) {
  11. o->lru = (LFUGetTimeInMinutes()<<8) | LFU_INIT_VAL;
  12. } else {
  13. o->lru = LRU_CLOCK();
  14. }
  15. return o;
  16. }

counter会被初始化为LFU_INIT_VAL,默认5。

pool

pool算法就与LRU算法一致了:

  1. if (server.maxmemory_policy & (MAXMEMORY_FLAG_LRU|MAXMEMORY_FLAG_LFU) ||
  2. server.maxmemory_policy == MAXMEMORY_VOLATILE_TTL)

计算idle时有所不同:

  1. } else if (server.maxmemory_policy & MAXMEMORY_FLAG_LFU) {
  2. /* When we use an LRU policy, we sort the keys by idle time
  3. * so that we expire keys starting from greater idle time.
  4. * However when the policy is an LFU one, we have a frequency
  5. * estimation, and we want to evict keys with lower frequency
  6. * first. So inside the pool we put objects using the inverted
  7. * frequency subtracting the actual frequency to the maximum
  8. * frequency of 255. */
  9. idle = 255-LFUDecrAndReturn(o);

使用了255-LFUDecrAndReturn(o)当做排序的依据。

参考链接

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对w3xue的支持。

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号