SETRANGE key offset value
起始版本:2.2.0 时间复杂度 O(1), not couting the time taken to copy the new string in palce. usually, this string is very small so the amoritized complexity is O(1). Otherwise, complexity is O(M) with M beingg the length of the value argument.
这个命令的作用是覆盖key对应的string的一部分,从指定的offset处开始,覆盖value的长度。如果offset比当前key对应string还要长,那这个string后面就补0以达到offset。不存在的keys被认为是空字符串,所以这个命令可以确保key有一个足够大的字符串,能在offset处设置value。
注意,offset最大可以是2^29 -1(536870911),因为redis字符串限制在512M大小。如果你需要超过这个大小,你可以用多个keys。
警告: 当set最后一个字节并且key还没有一个字符串value或者其value是个比较小的字符串时,Redis需要立即分配所有内存,这有可能会导致服务阻塞一会。
模式
正因为有了SETRANGE和类似功能的GETRANGE命令,你可以把Redis的字符串当成线性数组,随机访问只要O(1)复杂度。这在很多真实场景应用里非常快和高效。
返回值
integer - reply: 该命令修改后的字符串长度
例子
基本用法
> SET key1 "Hello World"
OK
> SETRANGE key1 6 "Redis"
(integer) 11
> GET key1
"Hello Redis"
>
补0的例子:
127.0.0.1:32768> SETRANGE key2 6 "Redis"
(integer) 11
127.0.0.1:32768> GET key2
"\x00\x00\x00\x00\x00\x00Redis"
127.0.0.1:32768>