Redis的value超过限制会怎样?
一、面试题
-
问:Redis的key和value限制是多少?
-
答:512MB
-
问:保存一个超过512MB的value会怎么样?
-
答:额…,我没试过,应该会报错吧,
-
你可以动手试试…
二、验证
- 代码
public static void main(String[] args) {
Jedis jedis = JedisFactory.getJedis();
jedis.set("test", "123");
byte[] bytes = new byte[1024 * 1024];
String str = new String(bytes);
//每次append 1MB的内容,尝试512次
for (int i = 0; i < 512; i++) {
jedis.append("test", str);
}
}
输出:
Exception in thread "main" redis.clients.jedis.exceptions.JedisDataException: ERR string exceeds maximum allowed size (512MB)
at redis.clients.jedis.Protocol.processError(Protocol.java:153)
at redis.clients.jedis.Protocol.process(Protocol.java:187)
at redis.clients.jedis.Protocol.read(Protocol.java:241)
at redis.clients.jedis.Connection.readProtocolWithCheckingBroken(Connection.java:309)
at redis.clients.jedis.Connection.getIntegerReply(Connection.java:260)
at redis.clients.jedis.Jedis.append(Jedis.java:689)
at com.intellif.mozping.data.HashRedis.setValue(HashRedis.java:30)
at com.intellif.mozping.data.HashRedis.main(HashRedis.java:21)
- 从输出我们看到,它提示我们value超过512MB的限制了:JedisDataException: ERR string exceeds maximum allowed size (512MB)
三、结论
- 因此,之前的答案是会抛出异常,下次遇到这个问题我们可以给与肯定的回复了。我们再看看redis的内存情况:
192.168.xx.xx:6379> INFO memory
# Memory
used_memory:537773302
used_memory_human:512.86M
used_memory_rss:557494272
used_memory_rss_human:531.67M
used_memory_peak:634557234
used_memory_peak_human:605.16M
used_memory_peak_perc:84.75%
used_memory_overhead:902569
used_memory_startup:852779
used_memory_dataset:536870733
used_memory_dataset_perc:99.99%
total_system_memory:134898106368
total_system_memory_human:125.63G
used_memory_lua:37888
used_memory_lua_human:37.00K
maxmemory:0
maxmemory_human:0B
maxmemory_policy:noeviction
mem_fragmentation_ratio:1.04
mem_allocator:libc
active_defrag_running:0
lazyfree_pending_objects:0
- 我们看到 used_memory:537773302,大概在计算在512.86MB左右,因此是符合基本情况的,redis没有保存其他key。
- 另外我们在使用redis的时候key尽量短小精悍会比较好,vaule也不宜太大,保存这么大的字符串也比较浪费内存资源,而且光是网络IO就得好长时间了吧。