redis键名长度如何影响性能的?

键名太长,性能不好,大家都这样说,太短不方面记忆阅读,我看了看自己用的最长的键长度50个字符,这算长吗?对性能影响有多少呢?如何评估呢?就是如何测试性能?

阅读 38.5k
2 个回答

官方涉及到的文章:An introduction to Redis data types and abstractionsRedis keys章节
原文:

Redis keys are binary safe, this means that you can use any binary sequence as a key, from a string like "foo" to the content of a JPEG file. The empty string is also a valid key.

A few other rules about keys:

  • Very long keys are not a good idea. For instance a key of 1024 bytes is a bad idea not only memory-wise, but also because the lookup of the key in the dataset may require several costly key-comparisons. Even when the task at hand is to match the existence of a large value, hashing it (for example with SHA1) is a better idea, especially from the perspective of memory and bandwidth.
  • Very short keys are often not a good idea. There is little point in writing "u1000flw" as a key if you can instead write "user:1000:followers". The latter is more readable and the added space is minor compared to the space used by the key object itself and the value object. While short keys will obviously consume a bit less memory, your job is to find the right balance.
  • Try to stick with a schema. For instance "object-type:id" is a good idea, as in "user:1000". Dots or dashes are often used for multi-word fields, as in comment:1234:reply.to or comment:1234:reply-to.

The maximum allowed key size is 512 MB.

我翻译的这篇文章:
Redis深入系列-0x014:Redis数据类型和概念介绍(上)0x001 Redis的key章节

Redis的key是比特安全的,这意味着你可以使用任何的二进制序列作为key,从像foo的字符串到一个JPEG文件的内容。甚至空字符串也是可以的。

关于key有一些其他的规则:

  • 非常长的key是不推荐的。一个1024 bytes是一个非常坏的注意,不仅仅是因为内存浪费,更是因为在数据集中搜索对比的时候需要耗费更多的成本。当要处理的是匹配一个非常大的值,从内存和带宽的角度来看,使用这个值的hash值是更好的办法(比如使用SHA1)。
  • 特别短的key通常也是不推荐的。在写像u100flw这样的键的时候,有一个小小的要点,我们可以用user:1000:followers代替。可读性更好,对于key对象和value对象增加的空间占用与此相比来说倒是次要的。当短的key可以很明显减少空间占用的时候,你的工作就是找到正确的平衡
  • 尝试去固定一个密室。比如object-type:id是一个好主意,-和.通常用于多个字符的域,就像comment:1234:reply.to,或者comment:1234:reply-to
  • 最大的key允许512MB

以上仅供参考

使用的key在保证能表明存的是什么数据的情况下尽可能的短即可。
比如key="article_view_top_10" 表示浏览量最高的10篇文章。
50个字符算长了,用了redis这么长时间了,真的没有用过这么长的key。
千里之堤毁于蚁穴,对性能影响又大多,没有评估过。长的key意味着占用更多的内存,意味着查找匹配的时候消耗更多的时间,很多时候,遵循规范即可。

宣传栏