设置Redis最大占用内存
Redis需要设置最大占用内存吗?如果Redis内存使用超出了设置的最大值会怎样?
设置Redis最大占用内存
Redis设置最大占用内存,打开redis配置文件,找到如下段落,设置maxmemory参数,maxmemory是bytes字节类型,注意转换。修改如下所示:
# In short... if you have slaves attached it is suggested that you set a lower
# limit for maxmemory so that there is some free RAM on the system for slave
# output buffers (but this is not needed if the policy is 'noeviction').
#
# maxmemory <bytes>
maxmemory 268435456
本机服务器redis配置文件路径:/etc/redis/6379.conf,由于本机自带内存只有1G,一般推荐Redis设置内存为最大物理内存的四分之三,所以设置0.75G,换成byte是751619276.
可以在CentOS下输入命令:find / -name redis查找redis目录:
[root@iZ94r80gdghZ ~]# find / -name redis
/usr/share/nginx/html/blog.tanteng.me/wp-content/cache/supercache/blog.tanteng.me/tag/redis
/etc/redis
/var/redis
Redis配置文件一般在etc下的redis安装目录下。
Redis使用超过设置的最大值
如果Redis的使用超过了设置的最大值会怎样?我们来改一改上面的配置,故意把最大值设为1个byte试试。
# output buffers (but this is not needed if the policy is 'noeviction').
#
# maxmemory <bytes>
maxmemory 1
打开debug模式下的页面,提示错误:OOM command not allowed when used memory > ‘maxmemory’.
设置了maxmemory的选项,redis内存使用达到上限。可以通过设置LRU算法来删除部分key,释放空间。默认是按照过期时间的,如果set时候没有加上过期时间就会导致数据写满maxmemory。
如果不设置maxmemory或者设置为0,64位系统不限制内存,32位系统最多使用3GB内存。
LRU是Least Recently Used 近期最少使用算法。
- volatile-lru -> 根据LRU算法生成的过期时间来删除。
- allkeys-lru -> 根据LRU算法删除任何key。
- volatile-lfu -> 根据设置过期时间,删除最少使用的key (实际过程中比较常用的方式配置)
- allkeys-lfu -> 所有的key,删除最少使用的key
- volatile-random -> 根据过期设置来随机删除key。
- allkeys->random -> 无差别随机删。
- volatile-ttl -> 根据最近过期时间来删除(辅以TTL)
- noeviction -> 谁也不删,直接在写操作时返回错误。
LRU和LFU字段解释:
# LRU means Least Recently Used 针对时间最少使用
# LFU means Least Frequently Used 针对动作最少使用,即访问次数
如果设置了maxmemory,一般都要设置过期策略。打开Redis的配置文件有如下描述,Redis有八种过期策略:
# volatile-lru -> Evict using approximated LRU among the keys with an expire set.
# allkeys-lru -> Evict any key using approximated LRU.
# volatile-lfu -> Evict using approximated LFU among the keys with an expire set.
# allkeys-lfu -> Evict any key using approximated LFU.
# volatile-random -> Remove a random key among the ones 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 evict anything, just return an error on write operations.
那么打开配置文件,添加如下一行,使用volatile-lfu的过期策略:
maxmemory-policy volatile-lfu