【Redis内存策略】

Redis最大内存的设置是通过设置maxmemory来完成的,格式为maxmemory bytes ,当目前使用的内存超过了设置的最大内存,就要进行内存释放了, 当需要进行内存释放的时候,需要用某种策略对保存的的对象进行删除。Redis有六种策略(默认的策略是noeviction)

Redis最大内存设置

默认情况下,在32位OS中,Redis最大使用3GB的内存,在64位OS中则没有限制。

在使用Redis时,应该对数据占用的最大空间有一个基本准确的预估,并为Redis设定最大使用的内存,

否则在64位OS中Redis会无限制地占用内存(当物理内存被占满后会使用swap空间),容易引发各种各样的问题。

通过如下配置控制Redis使用的最大内存:

maxmemory 100mb

在内存占用达到了maxmemory后,再向Redis写入数据时,Redis会:

1)根据配置的数据淘汰策略尝试淘汰数据,释放空间

扫描二维码关注公众号,回复: 428353 查看本文章

2)如果没有数据可以淘汰,或者没有配置数据淘汰策略,那么Redis会对所有写请求返回错误,但读请求仍然可以正常执行

 maxmemory <bytes>

# MAXMEMORY POLICY: how Redis will select what to remove when maxmemory

# is reached. You can select among five behaviors:

#

# volatile-lru -> remove the key with an expire set using an LRU algorithm

# allkeys-lru -> remove any key accordingly to the LRU algorithm

# volatile-random -> remove a random key with an expire set

# allkeys-random -> remove a random key, any key

# volatile-ttl -> remove the key with the nearest expire time (minor TTL)

# noeviction -> don't expire at all, just return an error on write operations

#

# Note: with any of the above policies, Redis will return an error on write

#       operations, when there are not suitable keys for eviction.

#

#       At the date of writing this 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

Redis提供了下面几种淘汰策略供用户选择,其中默认的策略为noeviction策略:

1)noeviction:当内存使用达到阈值的时候,所有引起申请内存的命令会报错。

2)allkeys-lru:在主键空间中,优先移除最近未使用的key。

3)volatile-lru:在设置了过期时间的键空间中,优先移除最近未使用的key。

4)allkeys-random:在主键空间中,随机移除某个key。

5)volatile-random:在设置了过期时间的键空间中,随机移除某个key。

6)volatile-ttl:在设置了过期时间的键空间中,具有更早过期时间的key优先移除。

淘汰策略的选择可以通过下面的配置指定:

# maxmemory-policy noeviction

猜你喜欢

转载自gaojingsong.iteye.com/blog/2409910