Redis基本数据类型—字符串类型
字符串类型是Redis中最基本的数据类型,它可以存储任何形式的字符串,包括二进制数据。其他的类型都是以字符串类型为基础,可以看作是字符串类型的不同组织形式。
1、赋值与取值
格式
redis> SET key value # 单个key赋值
redis> MSET key1 value1 key2 value2 [key value…] # 多个key赋值
redis> GET key # 获取单个key值
redis> MGET key1 key2 [key …] # 获取多个key值
举例
127.0.0.1:6379> SET foo hello
OK
127.0.0.1:6379> MSET a 1 b 2
OK
127.0.0.1:6379> GET foo
"hello"
127.0.0.1:6379> MGET a b
1) "1"
2) "2"
2、递增递减数字
格式
redis> INCR key # key自增1,如果不存在,则默认是0
redis> INCRBY key increment # key自增 increment
redis> DECR key # key自减1
redis> DECRBY key increment # key自减 increment
redis> INCRBYFLOAT key increment # key增加一个双精度浮点数 increment
举例
127.0.0.1:6379> INCR num
(integer) 1
127.0.0.1:6379> INCR num
(integer) 2
127.0.0.1:6379> DECR num
(integer) 1
127.0.0.1:6379> DECR num
(integer) 0
127.0.0.1:6379> INCRBY num 5
(integer) 5
127.0.0.1:6379> DECRBY num 2
(integer) 3
127.0.0.1:6379> INCRBYFLOAT num 5.9
"8.9"
127.0.0.1:6379> INCRBYFLOAT num 5E+4
3、向尾部追加值
格式
redis> APPEND key value # 在key的值后面追加值value
举例
127.0.0.1:6379> GET foo
"hello"
127.0.0.1:6379> APPEND foo " world!" # 因为有空格,需要用双引号以示区分
(integer) 12
127.0.0.1:6379> GET foo
"hello world!"
4、获取字符串长度
格式
redis> STRLEN key # 获取字符串key的值的长度
举例
127.0.0.1:6379> SET foo hello
OK
127.0.0.1:6379> STRLEN foo
(integer) 5
127.0.0.1:6379> SET foo 你好 # “你”和“好”的中文UTF-8编码长度为3
OK
127.0.0.1:6379> STRLEN foo
(integer) 6
5、位操作
格式
redis> GETBIT key offset # 获取key的二进制表示中第offset的位置的值
redis> SETBIT key offset value # 设置key的二进制表示中第offset的位置的值为value
redis> BITCOUNT key [start] [end] # 统计start与end字节之间1的个数
redis> BITOP operation destroy key [key …] # 对多个key进行位操作,结果存到destroy中
redis> BITPOS key value [start] [end] # 获取start与value字节之间键值为value的偏移量,从0开始
举例
127.0.0.1:6379> SET foo bar
OK
127.0.0.1:6379> GETBIT foo 0
(integer) 0
127.0.0.1:6379> GETBIT foo 6
(integer) 1
127.0.0.1:6379> GETBIT foo 10000 # 当索引超过实际长度时默认为0
(integer) 0
127.0.0.1:6379> SETBIT foo 6 0
(integer) 1
127.0.0.1:6379> SETBIT foo 7 1
(integer) 0
127.0.0.1:6379> GET foo
"aar"
127.0.0.1:6379> BITCOUNT foo # 统计值为1的二进制位个数
(integer) 10
127.0.0.1:6379> BITCOUNT foo 0 1 # 统计前两个字节包含的二进制值为1的个数
(integer) 6
位操作:AND、OR、XOR、NOT
127.0.0.1:6379> SET fool1 bar
OK
127.0.0.1:6379> GET fool1
"bar"
127.0.0.1:6379> SET fool2 aar
OK
127.0.0.1:6379> GET fool2
"aar"
127.0.0.1:6379> BITOP OR res fool1 fool2 # OR运算
(integer) 3
127.0.0.1:6379> GET res
"car"
127.0.0.1:6379>
BITPOS
127.0.0.1:6379> GET foo
"bar"
127.0.0.1:6379> BITPOS foo 1
(integer) 1
127.0.0.1:6379> BITPOS foo 0
(integer) 0
127.0.0.1:6379> BITPOS foo 1 1 2 # 查找第1和2个字节之间二进制值为1的偏移量
(integer) 9
注:偏移量总是从头算起,与字节无关,如果二进制值全是1,则0的偏移量为键值长度的下一个字节的偏移量,这是因为redis会默认为键值长度之后的二进制位都是0.
还没有评论,来说两句吧...