Home >Backend Development >PHP Problem >What should I do if PHP uses redis and there is insufficient memory?
Solution to insufficient memory when using redis in php: 1. Set the maximum memory size of Redis to 100M through the configuration file or command; 2. Get the current memory elimination policy; 3. Through "config set maxmemory-policy allkeys- lru" command to modify the elimination strategy.
本教程操作环境:windows7系统、PHP8.1版、Dell G3电脑。
我们知道Redis是基于内存的key-value数据库,因为系统的内存大小有限,所以我们在使用Redis的时候可以配置Redis能使用的最大的内存大小。
通过在Redis安装目录下面的redis.conf配置文件中添加以下配置设置内存大小
//设置Redis最大占用内存大小为100M maxmemory 100mb
redis的配置文件不一定使用的是安装目录下面的redis.conf文件,启动redis服务的时候是可以传一个参数指定redis的配置文件的
Redis支持运行时通过命令动态修改内存大小
//设置Redis最大占用内存大小为100M 127.0.0.1:6379> config set maxmemory 100mb //获取设置的Redis能使用的最大内存大小 127.0.0.1:6379> config get maxmemory
如果不设置最大内存大小或者设置最大内存大小为0,在64位操作系统下不限制内存大小,在32位操作系统下最多使用3GB内存
既然可以设置Redis最大占用内存大小,那么配置的内存就有用完的时候。那在内存用完的时候,还继续往Redis里面添加数据不就没内存可用了吗?实际上Redis定义了几种策略用来处理这种情况:noeviction(默认策略):对于写请求不再提供服务,直接返回错误(DEL请求和部分特殊请求除外)allkeys-lru:从所有key中使用LRU算法进行淘汰volatile-lru:从设置了过期时间的key中使用LRU算法进行淘汰allkeys-random:从所有key中随机淘汰数据volatile-random:从设置了过期时间的key中随机淘汰volatile-ttl:在设置了过期时间的key中,根据key的过期时间进行淘汰,越早过期的越优先被淘汰
当使用 volatile-lru、 volatile-random、 volatile-ttl这三种策略时,如果没有key可以被淘汰,则和 noeviction一样返回错误
获取当前内存淘汰策略:
127.0.0.1:6379> config get maxmemory-policy
通过配置文件设置淘汰策略(修改redis.conf文件):
maxmemory-policy allkeys-lru
通过命令修改淘汰策略:
127.0.0.1:6379> config set maxmemory-policy allkeys-lru
上面说到了Redis可使用最大内存使用完了,是可以使用LRU算法进行内存淘汰的,那么什么是LRU算法呢?
LRU (Least Recently Used), which is the least recently used, is a cache replacement algorithm. When using memory as a cache, the size of the cache is generally fixed. When the cache is full and you continue to add data to the cache, you need to eliminate some old data and free up memory space to store new data. At this time, the LRU algorithm can be used. The core idea is: if a piece of data has not been used in the recent period, the possibility of being used in the future is very small, so it can be eliminated.
Redis uses the approximate LRU algorithm, which is similar to the conventional The LRU algorithm is not quite the same. The approximate LRU algorithm eliminates data through random sampling, randomly selecting 5 (default) keys each time, and eliminating the least recently used keys.
The number of samples can be modified through the maxmemory-samples parameter: Example: maxmemory-samples 10 The larger the maxmenory-samples configuration, the closer the elimination result is to the strict LRU algorithm
In order to achieve approximation, Redis The LRU algorithm adds an additional 24-bit field to each key to store the last time the key was accessed.
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of What should I do if PHP uses redis and there is insufficient memory?. For more information, please follow other related articles on the PHP Chinese website!