SETRANGE key offset value

SETRANGE 命令从偏移量 offset 开始, 用 value 参数覆盖键 key 储存的字符串值。

不存在的键 key 当作空白字符串处理。

SETRANGE 命令会确保字符串足够长以便将 value 设置到指定的偏移量上, 如果键 key 原来储存的字符串长度比偏移量小(比如字符串只有 5 个字符长,但你设置的 offset10 ), 那么原字符和偏移量之间的空白将用零字节(zerobytes, "\x00" )进行填充。

因为 Redis 字符串的大小被限制在 512 兆(megabytes)以内, 所以用户能够使用的最大偏移量为 229-1(536870911) , 如果你需要使用比这更大的空间, 请使用多个 key

Warning: 当生成一个很长的字符串时, Redis 需要分配内存空间, 该操作有时候可能会造成服务器阻塞(block)。 在2010年出产的Macbook Pro上, 设置偏移量为 536870911(512MB 内存分配)将耗费约 300 毫秒, 设置偏移量为 134217728(128MB 内存分配)将耗费约 80 毫秒, 设置偏移量 33554432(32MB 内存分配)将耗费约 30 毫秒, 设置偏移量为 8388608(8MB 内存分配)将耗费约 8 毫秒。

*Patterns

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.

*返回值

整数: SETRANGE 命令会返回被修改之后, 字符串值的长度。

*例子

Basic usage:

redis>  SET key1 "Hello World"
"OK"
redis>  SETRANGE key1 6 "Redis"
(integer) 11
redis>  GET key1
"Hello Redis"
redis> 

Example of zero padding:

redis>  SETRANGE key2 6 "Redis"
(integer) 11
redis>  GET key2
"\u0000\u0000\u0000\u0000\u0000\u0000Redis"
redis>