以下是Redis中常用的关于Key的操作示例:
# 查看当前库中所有的key
127.0.0.1:6379> KEYS *
(empty array)
# 设置key
127.0.0.1:6379> set k1 v1
OK
127.0.0.1:6379> set k2 v2
OK
127.0.0.1:6379> set key3 value3
OK
127.0.0.1:6379> keys *
1) "key3"
2) "k2"
3) "k1"
# 判断key是否存在
127.0.0.1:6379> EXISTS k1
(integer) 1
127.0.0.1:6379> EXISTS k4
(integer) 0
# 判断多个key是否存储,返回存在的数量
127.0.0.1:6379> EXISTS k1 k2 k4
(integer) 2
# 查看key的类型
127.0.0.1:6379> TYPE k1
string
127.0.0.1:6379> LPUSH list1 12 3
(integer) 2
127.0.0.1:6379> TYPE list1
list
# 删除key
127.0.0.1:6379> DEL list1
(integer) 1
# 非阻塞删除,仅将key从keyspace删除
127.0.0.1:6379> UNLINK list1
(integer) 0
# 查看key的过期时间, -1:永不过期 -2:已过期
127.0.0.1:6379> TTL k1
(integer) -1
# 设置key的过期时间
127.0.0.1:6379> EXPIRE k1 10
(integer) 1
127.0.0.1:6379> TTL k1
(integer) 6
127.0.0.1:6379> TTL k1
(integer) 1
127.0.0.1:6379> TTL k1
(integer) 0
127.0.0.1:6379> TTL k1
(integer) -2
# 切换数据库
127.0.0.1:6379> SELECT 1
OK
127.0.0.1:6379[1]> KEYS *
(empty array)
127.0.0.1:6379[1]> SELECT 0
OK
# 将当前数据库中的key移动至指定数据库中
127.0.0.1:6379> MOVE k2 1
(integer) 1
127.0.0.1:6379> SELECT 1
OK
127.0.0.1:6379[1]> KEYS *
1) "k2"
127.0.0.1:6379[1]> SELECT 0
OK
# 查看当前数据库中key的数据
127.0.0.1:6379> DBSIZE
(integer) 1
127.0.0.1:6379> KEYS *
1) "key3"
# 清空当前数据库
127.0.0.1:6379> FLUSHDB
OK
127.0.0.1:6379> KEYS *
(empty array)
127.0.0.1:6379> SELECT 1
OK
127.0.0.1:6379[1]> DBSIZE
(integer) 1
# 清空所有数据库,在数据库0中执行,数据库1中的数据也会被清空
127.0.0.1:6379[1]> SELECT 0
OK
127.0.0.1:6379> FLUSHALL
OK
127.0.0.1:6379> SELECT 1
OK
127.0.0.1:6379[1]> DBSIZE
(integer) 0
声明:本作品采用署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0)[1]进行许可,使用时请注明出处。 Author: mengbin[2] blog: mengbin[3] Github: mengbin92[4] cnblogs: 恋水无意[5] 腾讯云开发者社区:孟斯特[6]
[1]
署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0): https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh
[2]
mengbin: mengbin1992@outlook.com
[3]
mengbin: https://mengbin.top
[4]
mengbin92: https://mengbin92.github.io/
[5]
恋水无意: https://www.cnblogs.com/lianshuiwuyi/
[6]
孟斯特: https://cloud.tencent.com/developer/user/6649301