Redis运行中监控内存的使用情况:
如果只做缓存使用,需要配置上lru策略。
maxmemory-policy allkeys-lru
maxmemory-samples 5
maxmemory?-?policy?allkeys?-?lru
maxmemory?-?samples?5
如果做持久化存储说明,内存也不够用了。需要考虑增加内存。
故障现场要看一下Redis的info输出,看看内存配是否达到了上限。
redis可以被作为类似memcached的应用级缓存使用,在内存超过限制时,按照配置的策略,淘汰掉相应的kv,使得内存可以继续留有足够的空间保存新的数据。
redis的conf文件中有对该机制的一份很好的解释:
194 # Don't use more memory than the specified amount of bytes.
195 # When the memory limit is reached Redis will try to remove keys
196 # accordingly to the eviction policy selected (see maxmemmory-policy).
197 #
198 # If Redis can't remove keys according to the policy, or if the policy is
199 # set to 'noeviction', Redis will start to reply with errors to commands
200 # that would use more memory, like SET, LPUSH, and so on, and will continue
201 # to reply to read-only commands like GET.
202 #
203 # This option is usually useful when using Redis as an LRU cache, or to set
204 # an hard memory limit for an instance (using the 'noeviction' policy).
205 #
206 # WARNING: If you have slaves attached to an instance with maxmemory on,
207 # the size of the output buffers needed to feed the slaves are subtracted
208 # from the used memory count, so that network problems / resyncs will
209 # not trigger a loop where keys are evicted, and in turn the output
210 # buffer of slaves is full with DELs of keys evicted triggering the deletion
211 # of more keys, and so forth until the database is completely emptied.
212 #
213 # In short... if you have slaves attached it is suggested that you set a lower
214 # limit for maxmemory so that there is some free RAM on the system for slave
215 # output buffers (but this is not needed if the policy is 'noeviction').
216 #
217 # maxmemory
注意,在redis按照master-slave使用时,其maxmeory应设置的比实际物理内存稍小一些,给slave output buffer留有足够的空间。
redis支持如下五种缓存淘汰策略:
219 # MAXMEMORY POLICY: how Redis will select what to remove when maxmemory
220 # is reached? You can select among five behavior:
221 #
222 # volatile-lru -> remove the key with an expire set using an LRU algorithm
223 # allkeys-lru -> remove any key accordingly to the LRU algorithm
224 # volatile-random -> remove a random key with an expire set
225 # allkeys->random -> remove a random key, any key
226 # volatile-ttl -> remove the key with the nearest expire time (minor TTL)
227 # noeviction -> don't expire at all, just return an error on write operations
注释已经解释的很清楚了,不再赘述。
其缓存管理功能,由redis.c文件中的freeMemoryIfNeeded函数实现。如果maxmemory被设置,则在每次进行命令执行之前,该函数均被调用,用以判断是否有足够内存可用,释放内存或返回错误。