redis入门到精通 - 02 通用key操作命令

Redis对于key的操作命令

# 设置keys
127.0.0.1:6379> set site dbase.cc
OK
127.0.0.1:6379> set age 29
OK

# 查看当前年有key
127.0.0.1:6379> keys *
1) "age"
2) "site"
# 精确/模糊查询keys
127.0.0.1:6379> keys site
1) "site"

127.0.0.1:6379> keys s*
1) "site"

127.0.0.1:6379> keys si?e
1) "site"

127.0.0.1:6379> keys sit[ey]
1) "site"

# 返回随机key
127.0.0.1:6379> randomkey
"age"
127.0.0.1:6379> randomkey
"site"

# 查看key类型
127.0.0.1:6379> type age

# 判断key是否存在,返回1/0
127.0.0.1:6379> exists site
(integer) 1
127.0.0.1:6379> exists sit
(integer) 0

# 删除key(删除1个或多个键): 发生修改返回1,未发生修改返回0
127.0.0.1:6379> del age
(integer) 1

# 改名(给key赋一个新的key名)
127.0.0.1:6379> rename site wangzhi
OK

# 已存在要改的名 - 覆盖
127.0.0.1:6379> set site dbase.cc
OK
127.0.0.1:6379> set search baidu.com
OK
127.0.0.1:6379> rename site search
OK
127.0.0.1:6379> get search
"dbase.cc"

# 为了避免覆盖,使用renamenx,发生修改返回1,未发生修改返回0
127.0.0.1:6379> set site dbase.cc
OK
127.0.0.1:6379> set search baidu.com
OK
127.0.0.1:6379> keys *
1) "site"
2) "search"
127.0.0.1:6379> renamenx site search
(integer) 0

127.0.0.1:6379> get search
"baidu.com"

# move key
127.0.0.1:6379> move search 1
(integer) 1
127.0.0.1:6379> keys *
1) "site"
127.0.0.1:6379> select 1
OK
127.0.0.1:6379[1]> keys *
1) "search"

# 查询key的生命周期 ttl key,返回秒数,-1代表key永久有效/不存在
127.0.0.1:6379> select 0
OK
127.0.0.1:6379> keys *
1) "site"
127.0.0.1:6379> ttl site
(integer) -1
127.0.0.1:6379> ttl age
(integer) -2

# 设置生命周期,以秒为单位
127.0.0.1:6379> expire site 10
(integer) 1
127.0.0.1:6379> get site
"dbase.cc"
127.0.0.1:6379> get site
(nil)
127.0.0.1:6379> expire site 10
(integer) 0

# 设置生命周期,以毫秒为单位
127.0.0.1:6379> set site dbase.cc
OK
127.0.0.1:6379> ttl site
(integer) -1
127.0.0.1:6379> pexpire site 9000
(integer) 1
127.0.0.1:6379> pttl site
(integer) 3896
127.0.0.1:6379> pttl site
(integer) 216
127.0.0.1:6379> pttl site
(integer) -2

# 把指定key置为永久有效
127.0.0.1:6379> set site dbase.cc
OK
127.0.0.1:6379> ttl site
(integer) -1
127.0.0.1:6379> expire site 20
(integer) 1
127.0.0.1:6379> ttl site
(integer) 15
127.0.0.1:6379> persist site
(integer) 1
127.0.0.1:6379> ttl site
(integer) -1
127.0.0.1:6379> get site
"dbase.cc"

redis的databases

redis默认打开16个databases

cat /etc/redis/redis.conf | grep databases
#----------------------------------------------------------------------
# Set the number of databases. The default database is DB 0, you can select
# dbid is a number between 0 and 'databases'-1
databases 16
# Compress string objects using LZF when dump .rdb databases?
#----------------------------------------------------------------------

127.0.0.1:6379> select 1
OK
127.0.0.1:6379[1]> keys *
(empty list or set)
127.0.0.1:6379[1]> select 0
OK
127.0.0.1:6379> keys *
1) "site"
2) "search"
文章目录
  1. 1. Redis对于key的操作命令
  2. 2. redis的databases