美文网首页
四 redis内存淘汰策略思想

四 redis内存淘汰策略思想

作者: 爱编程的凯哥 | 来源:发表于2019-02-26 06:01 被阅读1次

    目标

    分析redis的内存淘汰策略, lru算法简介

    lru算法简介

    Least recently used(LRU,最近最少使用):根据数据的历史访问记录淘汰数据。

    lru算法

    缓存污染问题:对于业务系统的批量性操作造成部分数据临时活跃度升高情况,造成这部分数据热度极速增加,而批量操作完后,缓存数据将无用.

    优化---LRU-K算法

    在LRU的基础上,新增一个队列,用来计算数据的访问次数,只有在一定时间阈值内访问次数达到K次的数据,才会放到LRU队列中,如图


    lru-k

    redis淘汰策略

    redis对于过期key的处理方式有两种 分为2种:passive (被动)和active(主动):

    1. 被动--惰性删除:当一些客户端进行访问的时候,发现key已超时过期,删除此key

    2. 主动: Redis 每秒运行10次会定时检查操作,从相关的过期key集合中随机测试20个key,删除所有已过期的key,如果有超过25%的key过期,就再执行一次此操作

    但因为redis完全基于内存操作的,很容易出现内存不足的情况,此时可能内存中又存有大量无用或命中率不高的缓存数据,所以redis提供相应的内存回收策略,如下配置:

    # MAXMEMORY POLICY: how Redis will select what to remove when maxmemory
    # is reached. You can select among five behaviors:
    #最大内存策略:当到达最大使用内存时,你可以在下面5种行为中选择,Redis如何选择淘汰数据库键
    
    #当内存不足以容纳新写入数据时
    
    # volatile-lru -> remove the key with an expire set using an LRU algorithm
    # volatile-lru :在设置了过期时间的键空间中,移除最近最少使用的key。这种情况一般是把 redis 既当缓存,又做持久化存储的时候才用。
    
    # allkeys-lru -> remove any key according to the LRU algorithm
    # allkeys-lru : 移除最近最少使用的key (推荐)
    
    # volatile-random -> remove a random key with an expire set
    # volatile-random : 在设置了过期时间的键空间中,随机移除一个键,不推荐
    
    # allkeys-random -> remove a random key, any key
    # allkeys-random : 直接在键空间中随机移除一个键,弄啥叻
    
    # volatile-ttl -> remove the key with the nearest expire time (minor TTL)
    # volatile-ttl : 在设置了过期时间的键空间中,有更早过期时间的key优先移除 不推荐
    
    # noeviction -> don't expire at all, just return an error on write operations
    # noeviction : 不做过键处理,只返回一个写操作错误。 不推荐
    
    # Note: with any of the above policies, Redis will return an error on write
    #       operations, when there are no suitable keys for eviction.
    # 上面所有的策略下,在没有合适的淘汰删除的键时,执行写操作时,Redis 会返回一个错误。下面是写入命令:
    #       At the date of writing these commands are: set setnx setex append
    #       incr decr rpush lpush rpushx lpushx linsert lset rpoplpush sadd
    #       sinter sinterstore sunion sunionstore sdiff sdiffstore zadd zincrby
    #       zunionstore zinterstore hset hsetnx hmset hincrby incrby decrby
    #       getset mset msetnx exec sort
    
    # 过期策略默认是:
    # The default is:
    # maxmemory-policy noeviction
    

    参考博客:
    https://blog.csdn.net/love254443233/article/details/82598381
    https://blog.csdn.net/weixin_39982274/article/details/79276455
    https://www.cnblogs.com/junyuhuang/p/5805168.html
    https://www.cnblogs.com/junyuhuang/p/5993612.html
    https://blog.csdn.net/qq_28018283/article/details/80764518
    https://blog.csdn.net/qq_38423105/article/details/82720956

    相关文章

      网友评论

          本文标题:四 redis内存淘汰策略思想

          本文链接:https://www.haomeiwen.com/subject/kljpyqtx.html