五种基本数据结构
redis 的 key 一般是 String 类型,不过 value 的类型多种多样,
在官网 https://redis.io/docs/latest/commands/ 可以查看到不同的命令,或者通过控制台进行查询
127.0.0.1:6379> help
redis-cli 6.2.14
To get help about Redis commands type:"help @<group>" to get a list of commands in <group>"help <command>" for help on <command>"help <tab>" to get a list of possible help topics"quit" to exitTo set redis-cli preferences:":set hints" enable online hints":set nohints" disable online hints
Set your preferences in ~/.redisclirc
通用命令
127.0.0.1:6379> help @generic # 查看通用命令COPY source destination [DB destination-db] [REPLACE]summary: Copy a keysince: 6.2.0DEL key [key ...]summary: Delete a keysince: 1.0.0DUMP keysummary: Return a serialized version of the value stored at the specified key.since: 2.6.0EXISTS key [key ...]summary: Determine if a key existssince: 1.0.0EXPIRE key secondssummary: Set a key's time to live in secondssince: 1.0.0EXPIREAT key timestampsummary: Set the expiration for a key as a UNIX timestampsince: 1.2.0KEYS patternsummary: Find all keys matching the given pattern # 查看符合模板的所有keysince: 1.0.0MIGRATE host port key| destination-db timeout [COPY] [REPLACE] [AUTH password] [AUTH2 username password] [KEYS key]summary: Atomically transfer a key from a Redis instance to another one.since: 2.6.0MOVE key dbsummary: Move a key to another databasesince: 1.0.0OBJECT subcommand [arguments [arguments ...]]summary: Inspect the internals of Redis objectssince: 2.2.3PERSIST keysummary: Remove the expiration from a keysince: 2.2.0PEXPIRE key millisecondssummary: Set a key's time to live in millisecondssince: 2.6.0PEXPIREAT key milliseconds-timestampsummary: Set the expiration for a key as a UNIX timestamp specified in millisecondssince: 2.6.0PTTL keysummary: Get the time to live for a key in millisecondssince: 2.6.0RANDOMKEY -summary: Return a random key from the keyspacesince: 1.0.0RENAME key newkeysummary: Rename a keysince: 1.0.0RENAMENX key newkeysummary: Rename a key, only if the new key does not existsince: 1.0.0RESTORE key ttl serialized-value [REPLACE] [ABSTTL] [IDLETIME seconds] [FREQ frequency]summary: Create a key using the provided serialized value, previously obtained using DUMP.since: 2.6.0SCAN cursor [MATCH pattern] [COUNT count] [TYPE type]summary: Incrementally iterate the keys spacesince: 2.8.0SORT key [BY pattern] [LIMIT offset count] [GET pattern [GET pattern ...]] [ASC|DESC] [ALPHA] [STORE destination]summary: Sort the elements in a list, set or sorted setsince: 1.0.0TOUCH key [key ...]summary: Alters the last access time of a key(s). Returns the number of existing keys specified.since: 3.2.1TTL keysummary: Get the time to live for a keysince: 1.0.0TYPE keysummary: Determine the type stored at keysince: 1.0.0UNLINK key [key ...]summary: Delete a key asynchronously in another thread. Otherwise it is just as DEL, but non blocking.since: 4.0.0WAIT numreplicas timeoutsummary: Wait for the synchronous replication of all the write commands sent in the context of the current connectionsince: 3.0.0# 通过help [command] 可以查看一个命令的具体用法
127.0.0.1:6379> help KEYSKEYS patternsummary: Find all keys matching the given patternsince: 1.0.0group: generic
关于 KEYS 指令
# 查询所有的 key(在生产环境下,不推荐使用 keys 命令,因为在 key 过多的情况下,效率不高)
127.0.0.1:6379> keys *
1) "name"
2) "age"
127.0.0.1:6379># 查询以 a 开头的key
127.0.0.1:6379> keys a*
1) "age"
127.0.0.1:6379>
关于 TTL 指令
127.0.0.1:6379> expire age 10
(integer) 1127.0.0.1:6379> ttl age
(integer) 8127.0.0.1:6379> ttl age
(integer) 6127.0.0.1:6379> ttl age
(integer) -2127.0.0.1:6379> ttl age
(integer) -2 #当这个key过期了,那么此时查询出来就是-2 127.0.0.1:6379> keys *
(empty list or set)127.0.0.1:6379> set age 10 #如果没有设置过期时间
OK127.0.0.1:6379> ttl age
(integer) -1 # ttl的返回值就是-1
String 类型
常见命令有:
- SET:添加或者修改已经存在的一个String类型的键值对
- GET:根据key获取String类型的value
- MSET:批量添加多个String类型的键值对
- MGET:根据多个key获取多个String类型的value
- INCR:让一个整型的key自增1
- INCRBY:让一个整型的key自增并指定步长,例如:incrby num 2 让num值自增2
- INCRBYFLOAT:让一个浮点类型的数字自增并指定步长
- SETNX:添加一个String类型的键值对,前提是这个key不存在,否则不执行
- SETEX:添加一个String类型的键值对,并且指定有效期
贴心小提示:以上命令除了INCRBYFLOAT 都是常用命令
关于 INCR INCRBY DECY 指令
127.0.0.1:6379> get age
"10"127.0.0.1:6379> incr age //增加1
(integer) 11127.0.0.1:6379> get age //获得age
"11"127.0.0.1:6379> incrby age 2 //一次增加2
(integer) 13 //返回目前的age的值127.0.0.1:6379> incrby age 2
(integer) 15127.0.0.1:6379> incrby age -1 //也可以增加负数,相当于减
(integer) 14127.0.0.1:6379> incrby age -2 //一次减少2个
(integer) 12127.0.0.1:6379> DECR age //相当于 incr 负数,减少正常用法
(integer) 11127.0.0.1:6379> get age
"11"
关于 SETNX 指令
127.0.0.1:6379> help setnxSETNX key valuesummary: Set the value of a key, only if the key does not existsince: 1.0.0group: string127.0.0.1:6379> set name Jack //设置名称
OK
127.0.0.1:6379> setnx name lisi //如果key不存在,则添加成功
(integer) 0
127.0.0.1:6379> get name //由于name已经存在,所以lisi的操作失败
"Jack"
127.0.0.1:6379> setnx name2 lisi //name2 不存在,所以操作成功
(integer) 1
127.0.0.1:6379> get name2
"lisi"
Hash 类型
常见命令:
- HSET key field value:添加或者修改hash类型key的field的值
- HGET key field:获取一个hash类型key的field的值
- HMSET:批量添加多个hash类型key的field的值
- HMGET:批量获取多个hash类型key的field的值
- HGETALL:获取一个hash类型的key中的所有的field和value
- HKEYS:获取一个hash类型的key中的所有的field
- HINCRBY:让一个hash类型key的字段值自增并指定步长
- HSETNX:添加一个hash类型的key的field值,前提是这个field不存在,否则不执行
关于 HMSET 和 HMGET 指令
127.0.0.1:6379> HMSET heima:user:4 name HanMeiMei
OK
127.0.0.1:6379> HMSET heima:user:4 name LiLei age 20 sex man
OK
127.0.0.1:6379> HMGET heima:user:4 name age sex
1) "LiLei"
2) "20"
3) "man"
关于 HKEYS 和 HVALS 指令
127.0.0.1:6379> HKEYS heima:user:4
1) "name"
2) "age"
3) "sex"
127.0.0.1:6379> HVALS heima:user:4
1) "LiLei"
2) "20"
3) "man"
List 类型
常见命令:
- LPUSH key element ... :向列表左侧插入一个或多个元素
- LPOP key:移除并返回列表左侧的第一个元素,没有则返回nil
- RPUSH key element ... :向列表右侧插入一个或多个元素
- RPOP key:移除并返回列表右侧的第一个元素
- LRANGE key star end:返回一段角标范围内的所有元素
- BLPOP和BRPOP:与LPOP和RPOP类似,只不过在没有元素时等待指定时间,而不是直接返回nil
关于 LPUSH RPUSH LPOP RPOP 指令
127.0.0.1:6379> LPUSH users 1 2 3
(integer) 3
127.0.0.1:6379> RPUSH users 4 5 6
(integer) 6
127.0.0.1:6379> LPOP users
"3"
127.0.0.1:6379> RPOP users
"6"
关于 LRANGE 指令
127.0.0.1:6379> LRANGE users 1 2
1) "1"
2) "4"
Set 类型
Redis 的 Set 结构与 Java 中的 HashSet 类似,可以看做是一个 value 为 null 的 HashMap。因为也是一个 hash 表,因此具备与 HashSet 类似的特征:
- 无序
- 元素不可重复
- 查找快
- 支持交集.并集.差集等功能
Set类型的常见命令
- SADD key member ... :向set中添加一个或多个元素
- SREM key member ... : 移除set中的指定元素
- SCARD key: 返回set中元素的个数
- SISMEMBER key member:判断一个元素是否存在于set中
- SMEMBERS:获取set中的所有元素
- SINTER key1 key2 ... :求key1与key2的交集
- SDIFF key1 key2 ... :求key1与key2的差集
- SUNION key1 key2 ..:求key1和key2的并集
关于 SADD SMEMBERS SREM SISMEMBER SCARD 指令
127.0.0.1:6379> sadd s1 a b c
(integer) 3
127.0.0.1:6379> smembers s1
1) "c"
2) "b"
3) "a"
127.0.0.1:6379> srem s1 a
(integer) 1127.0.0.1:6379> SISMEMBER s1 a
(integer) 0127.0.0.1:6379> SISMEMBER s1 b
(integer) 1127.0.0.1:6379> SCARD s1
(integer) 2
案例
- 将下列数据用 Redis 的 Set 集合来存储:
- 张三的好友有:李四.王五.赵六
- 李四的好友有:王五.麻子.二狗
- 利用 Set 的命令实现下列功能:
- 计算张三的好友有几人
- 计算张三和李四有哪些共同好友
- 查询哪些人是张三的好友却不是李四的好友
- 查询张三和李四的好友总共有哪些人
- 判断李四是否是张三的好友
- 判断张三是否是李四的好友
- 将李四从张三的好友列表中移除
127.0.0.1:6379> SADD zs lisi wangwu zhaoliu
(integer) 3127.0.0.1:6379> SADD ls wangwu mazi ergou
(integer) 3127.0.0.1:6379> SCARD zs
(integer) 3127.0.0.1:6379> SINTER zs ls
1) "wangwu"127.0.0.1:6379> SDIFF zs ls
1) "zhaoliu"
2) "lisi"127.0.0.1:6379> SUNION zs ls
1) "wangwu"
2) "zhaoliu"
3) "lisi"
4) "mazi"
5) "ergou"127.0.0.1:6379> SISMEMBER zs lisi
(integer) 1127.0.0.1:6379> SISMEMBER ls zhangsan
(integer) 0127.0.0.1:6379> SREM zs lisi
(integer) 1127.0.0.1:6379> SMEMBERS zs
1) "zhaoliu"
2) "wangwu"
SortedSet 类型
Redis的SortedSet是一个可排序的set集合,与Java中的TreeSet有些类似,但底层数据结构却差别很大。SortedSet中的每一个元素都带有一个score属性,可以基于score属性对元素排序,底层的实现是一个跳表(SkipList)加 hash表。
SortedSet具备下列特性:
- 可排序
- 元素不重复
- 查询速度快
因为SortedSet的可排序特性,经常被用来实现排行榜这样的功能。
常见命令有:
- ZADD key score member:添加一个或多个元素到sorted set ,如果已经存在则更新其score值
- ZREM key member:删除sorted set中的一个指定元素
- ZSCORE key member : 获取sorted set中的指定元素的score值
- ZRANK key member:获取sorted set 中的指定元素的排名
- ZCARD key:获取sorted set中的元素个数
- ZCOUNT key min max:统计score值在给定范围内的所有元素的个数
- ZINCRBY key increment member:让sorted set中的指定元素自增,步长为指定的increment值
- ZRANGE key min max:按照score排序后,获取指定排名范围内的元素
- ZRANGEBYSCORE key min max:按照score排序后,获取指定score范围内的元素
- ZDIFF.ZINTER.ZUNION:求差集.交集.并集
注意:所有的排名默认都是升序,如果要降序则在命令的Z后面添加REV即可,例如:
- 升序获取 sorted set 中的指定元素的排名:ZRANK key member
- 降序获取 sorted set 中的指定元素的排名:ZREVRANK key memeber