本文内容为 http://redis.io/commands/setrange 的翻译、注解、例子扩充及其它修改。感谢 Redis 作者 Antirez 为开源社区作出的贡献,本文保证最新、最准、最全以表示对其的敬意。欢迎留言纠错、提示更新或支持。
SETRANGE key offset value

对存储在键 key 中的字符串,从指定偏移 offset 处开始,将值 value 整个覆写(Overwrite)进去。

Overwrites part of the string stored at key, starting at the specified offset, for the entire length of value.

如果偏移超出键 key 对应的字符串值的长度,该字符串将被用 0 值字节(Zero-byte)填充,以使偏移 offset 适用。

If the offset is larger than the current length of the string at key, the string is padded with zero-bytes to make offset fit. 

不存在的键被认为其对应的值为空字符串(Empty string),因此该命令会确保目标字符串足够大,使得能够在偏移 offset 处写入值 value

 Non-existing keys are considered as empty strings, so this command will make sure it holds a string large enough to be able to set value at offset.
  • 被该命令修改后的字符串的长度。

    the length of the string after it was modified by the command.
  • redis> SET key1 "Hello World"
    OK
    redis> SETRANGE key1 6 "Redis"
    (integer) 11
    redis> GET key1
    "Hello Redis"
  • 结合使用 SETRANGE 及有相似功能的命令 GETRANGE,你可以将 Redis 字符串当作一个线性数组来使用,随机访问的时间复杂度为 O(1)

    Thanks to SETRANGE and the analogous GETRANGE commands, you can use Redis strings as a linear array with O(1) random access. This is a very fast and efficient storage in many real world use cases.
  • 版本支持

    2.2.0+

    时间复杂度(Time complexity)

    O(1),不考虑就地拷贝新字符串的耗时。通常,该字符串非常小,使得平摊复杂度(Amortized complexity)O(1)。否则,时间复杂度将为 O(M),而 M 即为 value 参数的长度。

    Time complexity: O(1), not counting the time taken to copy the new string in place. Usually, this string is very small so the amortized complexity is O(1). Otherwise, complexity is O(M) with M being the length of the value argument.

    最大偏移限制

    该命令所能够设置的最大偏移 offset2^29 - 1(536870911),因为在 Redis 中,字符串被限制为 512MB,如果需要超过该限制,可以使用多个键。

    Note that the maximum offset that you can set is 229 -1 (536870911), as Redis Strings are limited to 512 megabytes. If you need to grow beyond this size, you can use multiple keys.

    一次性内存分配带来的性能问题

    Warning: When setting the last possible byte and the string value stored at key does not yet hold a string value, or holds a small string value, Redis needs to allocate all intermediate memory which can block the server for some time. On a 2010 MacBook Pro, setting byte number 536870911 (512MB allocation) takes ~300ms, setting byte number 134217728 (128MB allocation) takes ~80ms, setting bit number 33554432 (32MB allocation) takes ~30ms and setting bit number 8388608 (8MB allocation) takes ~8ms. Note that once this first allocation is done, subsequent calls to SETRANGE for the same key will not have the allocation overhead.