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

设置(Set)或清除(Clear)存储在键 key 中的字符串值(String Value)中指定偏移 offset 处的位(Bit)

Sets or clears the bit at offset in the string value stored at key

指定位位既可以被设置,也可以被清除,这取决值 value1 还是 0

The bit is either set or cleared depending on value, which can be either 0 or 1

当键 key 不存在时,一个新的字符串值将被创建。且该字符串将被扩展至足以容纳在编移 offset 处的位。

offset 的取值范围为:大于等于 0,且小于 232 次幂。该范围限制使用位图最大为 512MB

当字符串扩展时,新增位将被默认置为 0

When key does not exist, a new string value is created. The string is grown to make sure it can hold a bit at offset. The offset argument is required to be greater than or equal to 0, and smaller than 232 (this limits bitmaps to 512MB). When the string at key is grown, added bits are set to 0
  • 存储在偏移 offset 处的位的原始值。

    the original bit value stored at offset
  • redis> SETBIT mykey 7 1
    (integer) 0
    redis> SETBIT mykey 7 0
    (integer) 1
    redis> GET mykey
    "\u0000"
  • 版本支持

    2.2.0+

    时间复杂度(Time complexity)

    O(1)

    其它

    字符串扩展会有一定性能消耗。

    Warning: When setting the last possible bit (offset equal to 232 -1) 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 bit number 232 -1 (512MB allocation) takes ~300ms, setting bit number 230 -1 (128MB allocation) takes ~80ms, setting bit number 228 -1 (32MB allocation) takes ~30ms and setting bit number 226 -1 (8MB allocation) takes ~8ms. Note that once this first allocation is done, subsequent calls to SETBIT for the same key will not have the allocation overhead