Redis的数据结构及用法
本文最后更新于 2025年2月17日
未完待续
一、概述
Redis的数据结构指的是Value的数据结构类型,Key都是字符串。
以往版本常用的数据结构有String、List、Hash、Set、ZSet,Redis进化过程中又陆陆续续推出了GEO、HyperLogLog、Bitmap、Bitfleid、Stream这几种更加高级的数据结构,截止到目前的7.x版本,Redis共有10大数据结构。
Redis官网的介绍:https://redis.io/commands
二、String 字符串
2.1 概述
- String是最常用的数据类型,一个key对应一个value。
- String是二进制安全的,可以包含任何数据(例如图片和序列化对象),支持序列化。
- 单个Value最大512MB。
2.2 用法
命令行下输入
help @<type>
命令,redis服务器会返回该数据类型的所有用法
127.0.0.1:6379> help @string
APPEND key value
summary: Appends a string to the value of a key. Creates the key if it doesn't exist.
since: 2.0.0
DECR key
summary: Decrements the integer value of a key by one. Uses 0 as initial value if the key doesn't exist.
since: 1.0.0
DECRBY key decrement
summary: Decrements a number from the integer value of a key. Uses 0 as initial value if the key doesn't exist.
since: 1.0.0
GET key
summary: Returns the string value of a key.
since: 1.0.0
GETDEL key
summary: Returns the string value of a key after deleting the key.
since: 6.2.0
GETEX key [EX seconds|PX milliseconds|EXAT unix-time-seconds|PXAT unix-time-milliseconds|PERSIST]
summary: Returns the string value of a key after setting its expiration time.
since: 6.2.0
GETRANGE key start end
summary: Returns a substring of the string stored at a key.
since: 2.4.0
GETSET key value
summary: Returns the previous string value of a key after setting it to a new value.
since: 1.0.0
INCR key
summary: Increments the integer value of a key by one. Uses 0 as initial value if the key doesn't exist.
since: 1.0.0
INCRBY key increment
summary: Increments the integer value of a key by a number. Uses 0 as initial value if the key doesn't exist.
since: 1.0.0
INCRBYFLOAT key increment
summary: Increment the floating point value of a key by a number. Uses 0 as initial value if the key doesn't exist.
since: 2.6.0
LCS key1 key2 [LEN] [IDX] [MINMATCHLEN min-match-len] [WITHMATCHLEN]
summary: Finds the longest common substring.
since: 7.0.0
MGET key [key ...]
summary: Atomically returns the string values of one or more keys.
since: 1.0.0
MSET key value [key value ...]
summary: Atomically creates or modifies the string values of one or more keys.
since: 1.0.1
MSETNX key value [key value ...]
summary: Atomically modifies the string values of one or more keys only when all keys don't exist.
since: 1.0.1
PSETEX key milliseconds value
summary: Sets both string value and expiration time in milliseconds of a key. The key is created if it doesn't exist.
since: 2.6.0
SET key value [NX|XX] [GET] [EX seconds|PX milliseconds|EXAT unix-time-seconds|PXAT unix-time-milliseconds|KEEPTTL]
summary: Sets the string value of a key, ignoring its type. The key is created if it doesn't exist.
since: 1.0.0
SETEX key seconds value
summary: Sets the string value and expiration time of a key. Creates the key if it doesn't exist.
since: 2.0.0
SETNX key value
summary: Set the string value of a key only when the key doesn't exist.
since: 1.0.0
SETRANGE key offset value
summary: Overwrites a part of a string value with another by an offset. Creates the key if it doesn't exist.
since: 2.2.0
STRLEN key
summary: Returns the length of a string value.
since: 2.2.0
SUBSTR key start end
summary: Returns a substring from a string value.
since: 1.0.0
127.0.0.1:6379>
2.2.1 SET, GET
语法:
[ ]是可选的参数
SET key value [NX | XX] [GET] [EX seconds | PX milliseconds | EXAT unix-time-seconds | PXAT unix-time-milliseconds | KEEPTTL]
SET
命令有EX
、PX
、NX
、XX
以及KEEPTTL
五个可选参数,其中KEEPTTL
为6.0版本添加的可选参数,其它为2.6.12版本添加的可选参数。
EX seconds
以秒为单位设置过期时间PX milliseconds
以毫秒为单位设置过期时间EXAT timestamp
设置以秒为单位的UNIX时间戳所对应的时间为过期时间PXAT milliseconds-timestamp
设置以毫秒为单位的UNIX时间戳所对应的时间为过期时间NX
键不存在的时候设置键值XX
键存在的时候设置键值KEEPTTL
保留设置前指定键的生存时间GET
返回指定键原本的值,若键不存在时返回nil
SET
命令使用EX
、PX
、NX
参数,其效果等同于SETEX
、PSETEX
、SETNX
命令。根据官方文档的描述,未来版本中SETEX
、PSETEX
、SETNX
命令可能会被淘汰。
EX
,NX
可用于分布式锁。
案例:最常用的set/get
127.0.0.1:6379> set k1 v1
OK
127.0.0.1:6379> get k1
"v1"
案例:NX,键不存在才能创建,否则不能创建
127.0.0.1:6379> set k1 v1 nx
OK
127.0.0.1:6379> set k1 v1 nx
(nil)
案例:XX,已存在的才创建,否则不能创建
127.0.0.1:6379> set k1 v1
OK
127.0.0.1:6379> set k1 v1 xx
OK
127.0.0.1:6379> get k2
(nil)
127.0.0.1:6379> set k2 v2 xx
(nil)
案例:GET,设置新的值前先把旧的值返回
127.0.0.1:6379> set k1 v1
OK
127.0.0.1:6379> set k1 v2 get
"v1"
案例:EX,10秒过期
127.0.0.1:6379> set k1 v1 ex 10
OK
127.0.0.1:6379> ttl k1
(integer) 8
127.0.0.1:6379> ttl k1
(integer) 6
127.0.0.1:6379> ttl k1
(integer) 4
set ex是原子操作,和先set key value然后expire key是不同的,后者不是原子的
案例:PX,9000毫秒过期
127.0.0.1:6379> set k1 v1 px 9000
OK
127.0.0.1:6379> ttl k1
(integer) 7
127.0.0.1:6379> ttl k1
(integer) 5
127.0.0.1:6379> ttl k1
(integer) 4
案例:KEEPTTL
同一个key如果设置了新的值,又没有追加过期时间,redis会令其立即过期
127.0.0.1:6379> set k1 v1 ex 40
OK
127.0.0.1:6379> ttl k1
(integer) 37
127.0.0.1:6379> set k1 v2
OK
127.0.0.1:6379> ttl k1
(integer) -1
如果需要续接过期时间,就需要用到参数KEEPTTL,设置新值后,过期时间会被续接下来
127.0.0.1:6379> set k1 v1 ex 50
OK
127.0.0.1:6379> ttl k1
(integer) 46
127.0.0.1:6379> set k1 v1 keepttl
OK
127.0.0.1:6379> ttl k1
(integer) 33
2.2.2 MSET, MGET, MSETNX
案例:MSET同时设置和获取多个值
127.0.0.1:6379> mset k1 v1 k2 v2 k3 v3
OK
127.0.0.1:6379> mget k1 k2 k3
1) "v1"
2) "v2"
3) "v3"
案例 MSETNX,同时设置多个key的值,且key不存在才设置,只会同时成功或同时失败
失败,因为k1已经存在,k1没有成功修改,k2也根本存不进去
127.0.0.1:6379> flushdb
OK
127.0.0.1:6379> set k1 v1
OK
127.0.0.1:6379> msetnx k1 a1 k2 v2
(integer) 0
127.0.0.1:6379> get k1
"v1"
127.0.0.1:6379> get k2
(nil)
成功,k1,k2都不存在,全部添加成功
127.0.0.1:6379> flushdb
OK
127.0.0.1:6379> msetnx k1 v1 k2 v2
(integer) 1
127.0.0.1:6379> mget k1 k2
1) "v1"
2) "v2"
2.2.3 GETRANGE,SETRANGE
GETRANGE,类似Java中的substring()
,字符串截取, 0到-1代表不截取
案例:
127.0.0.1:6379> set k1 abcdefg
OK
127.0.0.1:6379> getrange k1 0 -1
"abcdefg"
127.0.0.1:6379> getrange k1 1 4
"bcde"
SETRANGE,从第几个字符开始设置新的内容
案例:
127.0.0.1:6379> set k1 abcdefg
OK
127.0.0.1:6379> setrange k1 1 xxyy
(integer) 7
127.0.0.1:6379> get k1
"axxyyfg"
2.2.4 INCR(BY),DECR(BY)
数值的加减,值一定要是数字才能进行这个操作
案例:INCR,每次执行加1
127.0.0.1:6379> set k1 100
OK
127.0.0.1:6379> get k1
"100"
127.0.0.1:6379> incr k1
(integer) 101
127.0.0.1:6379> incr k1
(integer) 102
127.0.0.1:6379> incr k1
(integer) 103
127.0.0.1:6379> incr k1
(integer) 104
案例:INCRBY,修改步长为5
127.0.0.1:6379> set k1 0
OK
127.0.0.1:6379> incrby k1 5
(integer) 5
127.0.0.1:6379> incrby k1 5
(integer) 10
127.0.0.1:6379> incrby k1 5
案例:DECR,递减1,DECRBY同理
127.0.0.1:6379> set k1 100
OK
127.0.0.1:6379> decr k1
(integer) 99
127.0.0.1:6379> decr k1
(integer) 98
127.0.0.1:6379> decr k1
(integer) 97
127.0.0.1:6379> set k1 100
OK
127.0.0.1:6379> decrby k1 5
(integer) 95
127.0.0.1:6379> decrby k1 5
(integer) 90
127.0.0.1:6379> decrby k1 5
(integer) 85
2.2.5 STRLEN
字符串长度
语法
strlen key
案例
127.0.0.1:6379> set k1 aaa
OK
127.0.0.1:6379> strlen k1
(integer) 3
2.2.6 APPEND
字符串追加
语法
APPEND key value
案例
127.0.0.1:6379> set k1 aaa
OK
127.0.0.1:6379> append k1 bbb
(integer) 6
127.0.0.1:6379> get k1
"aaabbb"
2.2.7 GETSET
getset,顾名思义,先取值在设置新的值进去,和set <key> <value> get
命令相同
127.0.0.1:6379> set k1 v1
OK
127.0.0.1:6379> getset k1 v2
"v1"
127.0.0.1:6379> get k1
"v2"
2.3 小结
字符串是一个最基本的数据结构,可用于分布式锁,点赞数量统计等场景。
三、List 列表
3.1 概述
- List是简单的字符串列表,单key多个value,按照插入顺序排序。
- 支持添加一个元素到列表的头部(左边)或者尾部(右边)。
- 它的底层实际是个双端链表,用在栈,队列,消息队列等场景,左右都可以插入,如果键不存在创建新的链表,键已存在,则新增内容,如果值全被移除了,对应的键也就消失了。
- 最多可以包含2³²-1个元素 (4294967295, 每个列表超过40亿个元素)。
3.2 用法
3.2.1 PUSH
3.2.1 POP
3.3 小结
四、Hash 哈希表
- Hash是一个String类型的field(字段)和value(值)的映射表,Hash特别适合用于存储对象。
- 每个Hash可以存储2³²-1个键值对 (40多亿)。
五、Set 集合
- Set是String类型的无序集合,集合成员是唯一的,这就意味着集合中不能出现重复的数据,集合对象的编码可以是intset或者hashtable。
- Set是通过哈希表实现的,所以添加,删除,查找的复杂度都是O(1)。
- Set中最大的成员数为2³²-1 (4294967295,每个集合可存储40多亿个成员)。
六、ZSet(SortedSet) 有序集合
- ZSet和Set一样也是String类型元素的集合,且不允许重复的成员,不同的是ZSet每个元素都会关联一个double类型的分数,Redis正是通过分数来为集合中的成员进行从小到大的排序。
- ZSet的成员是唯一的,但分数(score)却可以重复。
- ZSet集合是通过哈希表实现的,所以添加,删除,査找的复杂度都是O(1)。
- ZSet集合中最大的成员数为2³²-1。
七、GEO 地理空间
GEO主要用于存储地理位置信息,并对存储的信息进行操作,包括
- 添加地理位置的坐标
- 获取地理位置的坐标
- 计算两个位置之间的距离
- 根据用户给定的经纬度坐标来获取指定范围内的地理位置集合
八、HyperLogLog 基数统计
HyperLogLog是用来做基数统计的算法,HyperLogLog的优点是,在输入元素的数量或者体积非常非常大时,计算基数所需的空间总是固定且是很小的。
在Redis里面,每个HyperLogLog键只需要花费12KB内存,就可以计算接近2⁶⁴个不同元素的基数,这和计算基数时,元素越多耗费内存就越多的集合形成鲜明对比。
但是,因为HyperLogLog只会根据输入元素来计算基数,而不会储存输入元素本身,所以HyperLogLog不能像集合那样,返回输入的各个元素。
九、Bitmap 位图
由0和1状态表现的二进制位的bit数组(数组里每个元素只能是0或1)。
十、Bitfleid 位域
通过bitfield命令可以一次性操作多个比特位域(指的是连续的多个比特位),它会执行一系列操作并返回一个响应数组,这个数组中的元素对应参数列表中的相应操作的执行结果。
说白了就是通过bitfield命令我们可以一次性对多个比特位域进行操作。
十一、Stream 流
Redis Stream是Redis 5.0版本新增加的数据结构。
Redis Stream主要用于消息队列(MQ,Message Queue),Redis本身是有一个Redis发布订阅(pub/sub)来实现消息队列的功能,但它有个缺点就是消息无法持久化,如果出现网络断开、Redis宕机等,消息就会被丢弃,简单来说发布订阅(pub/sub)可以分发消息,但无法记录历史消息。
而Redis Stream提供了消息的持久化和主备复制功能,可以让任何客户端访问任何时刻的数据,并且能记住每一个客户端的访问位置,还能保证消息不丢失。