【Redis】基础命令数据结构
文章目录
- 基础命令
- keys
- exists
- del
- expire
- ttl
- type
- 数据结构和内部编码
在介绍数据类型前先介绍一下 Redis 的基础命令,方便理解
基础命令
keys
返回所有满足样式(pattern)的 key
keys pattern
当前有如下 key
PS
:实际开发环境和生产环境不建议使用keys *
。因为 keys 的时间复杂度是 O(N),redis 执行命令为单线程,如果数据量过大,可能会因此而阻塞,导致业务线程无法使用 redis,而造成阻塞或更严重的后果
支持如下样式
h?llo
:? 可匹配任意一个字符,如 hello,hallo,hxllo
h*llo
:* 可匹配任意零个或多个字符,如 hllo、heeeello
h[ae]llo
:[ ]可匹配其中任意一个字符,如 hello、hallo,不匹配 hillo、hllo
h[^e]llo
:[^e] 反向匹配,除了e都可以匹配,如 hallo、hbllo、…,不匹配 hello、hllo
h[a-e]llo
:[a-e] 表示匹配 a-e 范围的任意一个字符,如 hallo、hbllo、hcllo,不匹配 hello、hllo
exists
判断 key 是否存在,返回存在的个数
exists key [key …]
[ ] 是可选字段
数据同上,不支持样式
del
删除指定的 key,返回删除的个数
del key [key …]
expire
为指定的 key 添加秒级的过期时间(Time To Live TTL)
expire key seconds
返回值:1 表示设置成功,0表示设置失败
ttl
获取指定 key 的过期时间,秒级
ttl key
返回值:剩余过期时间,-1 表示没有关联过期时间,-2 表示 key 不存在
127.0.0.1:6379> keys *
1) "heeeeello"
2) "hello"
3) "hallo"
4) "hbllo"
127.0.0.1:6379> ttl hello
(integer) -1
127.0.0.1:6379> ttl hllo
(integer) -2
127.0.0.1:6379> expire hello 10
(integer) 1
127.0.0.1:6379> ttl hello
(integer) 6
127.0.0.1:6379> ttl hello
(integer) 5
127.0.0.1:6379> ttl hello
(integer) -2
expire 和 ttl 都有对应的支持毫秒为单位的版本:pexpire 和 pttl,用法相同
type
返回 key 对应的数据类型
type key
返回值:none
、string
、list
、set
、zset
、hash
、stream
添加数据的操作后续讲解
数据结构和内部编码
type 命令实际返回的是当前键的数据结构类型,分别为 string(字符串)、list(列表)、hash(哈希)、set(集合)、zset(有序结合),但这些只是 Redis 对外的数据结构
Redis 中 key 的数据结构都为 string,value 的数据结构有不同
实际 Redis 针对每种数据类型都有自己的底层内部编码实现,而且不同情况下,会有多种实现,适配不同的场景
数据结构:内部编码数据结构 | 内部编码 |
---|---|
string | raw 较长时使用 |
int 数字 | |
embstr 较短时使用 | |
hash | hashtable |
ziplist | |
list | linkedlist |
ziplist | |
quicklist | |
set | hashtable |
intset | |
zset | skiplist 跳表 |
ziplist |
可以使用 object encoding
查看 value 的内部编码
object encoding key
以上就是本篇博客的所有内容,感谢你的阅读
如果觉得本篇文章对你有所帮助的话,不妨点个赞支持一下博主,拜托啦,这对我真的很重要。