字符串是Redis最简单的储存类型,它存储的值可以是字符串、整数或者浮点数,对整个字符串或者字符串的其中一部分执行操作;对整数或者浮点数执行自增(increment)或者自减(decrement)操作。
Redis的字符串是一个由字节组成的序列,采用预分配冗余空间的方式来减少内存的频繁分配,内部为当前字符串实际分配的空间capacity 一般要高于实际字符串长度len。当字符串长度小于1M时,扩容都是加倍现有的空间,如果超过1M,扩容时一次只会多扩1M的空间。需要注意的是字符串最大长度为512M。
字符串类型在工作中使用广泛,主要用于缓存数据,提高查询性能。比如存储登录用户信息、电商中存储商品信息、可以做计数器(想知道什么时候封锁一个IP地址(访问超过几次))等等。
的字符串是动态字符串,是可以修改的字符串,内部结构如图中所示,内部为当前字符串实际
# SET key value [EX seconds|PX milliseconds|EXAT timestamp|PXAT milliseconds-timestamp] [NX|XX] [GET]
# 过期时间(可选参数) [EX(秒) |PX(毫秒) |EXAT(时间戳) |PXAT(毫秒时间戳) ]
# 是否设置 [NX(不存在时设置)|XX(存在时设置)]
# [GET] 是否同时获取旧值
> SET test 'hello word'
OK
# 设置过期时间为100s
> SET test1 'hello word' ex 100
OK
# 重复设置将会更新值和过期时间
> SET test 'hello c69p.com' get
"hello word"
# 存在时设置,同时获取旧值
> SET test 'chendasheng' xx get
"hello c69p.com"
# 设置多个键的字符串值
# MSET key value [key value ...]
> MSET test2 "is test2" test3 "is test3"
OK
# 设置多个键,不存在时,设置字符串值
# MSETNX key value [key value ...]
> MSET test4 "is test4" test5 "is test5"
OK
# 键不存在时,设置字符串值
# SETNX key value
> SETNX test6 "a"
(integer) 1
# 设置生存时间(秒为单位),同时设置值,存在则覆盖
# SETEX key seconds value (秒) | PSETEX key milliseconds value (毫秒)
> SETEX test7 100 "is test7"
OK
# 覆盖给定 key 所储存的字符串值
# SETRANGE key offset value
> SETRANGE test6 0 "chendasheng"
(integer) 11
创建多条是原子操作,一条不成功则所有的都不成功。
# 存在则返回,不存在返回nil
# GET key
> GET test6
"chendasheng"
# 获取(旧)值并设置新值
# GETSET key value
> GETSET test6 "im test6"
"chendasheng"
# MGET key [key ...]
> MGET test1 test6
1) (nil)
2) "im test6"
# STRLEN key
> STRLEN test6
(integer) 8
# TYPE key
> TYPE test6
string
# 数字值增一,不存在则新建一个
# INCR key
> INCR num
(integer) 1
# 自增增量值(increment)
# INCRBY key increment
> INCRBY num 10
(integer) 11
# 自增增量值浮点(increment)
# INCRBYFLOAT key increment
> INCRBY num 10.1
(integer) 22.1
# 数字值减一,不存在则新建一个
# DECR key
> DECR num1
(integer) -1
# 自减减量值(increment)
# DECRBY key increment
> DECRBY num1 10
(integer) -11
# 追加值
# APPEND key value
> APPEND test6 1
(integer) 9
bitmap并不是Redis
一种数据结构,实际上它就是字符串,但是可以对字符串的位进行操作。bitmap一套命令。可以把bitmap想象成一个以bit为单位的数组,数组的每个单元存储0和1,数组的下标叫做偏移量
# offset 偏移量 value值
# SETBIT key offset value
> SETBIT bittest 0 1
(integer) 0
# offset 偏移量
# GETBIT key offset
> GETBIT bittest 0
(integer) 1
用于统计字符串被设置为1的bit数
# 统计一个字符区间内为1的个数
# BITCOUNT key [start end]
> BITCOUNT bittest
(integer) 1
BITCOUNT是以字符为(Byte)单位,一个字符有8位bit
查找指定范围出现的第一个0或1的bit位置
# bit查找的值 0 或者 1 [start] [end] 开始结束范围
# BITPOS key bit [start] [end]
> BITPOS test 1 0
(integer) 1
# 对每bit进行运算
# BITOP operation destkey key [key ...]
> set key1 aa
OK
> set key2 bb
OK
> bitop and dest key1 key2
(integer) 2
> get dest
"``"
> bitop or dest key1 key2
(integer) 2
> get dest
"cc"