预备知识
Redis的五大数据类型是:String(字符串)、Hash(哈希)、List(列表)、Set(集合)和 zset(sorted set:有序集合)
String(字符串)- 存放一个地址信息
127.0.0.1:6379> set address "ᄆᄒ" //这里的乱码代表 中文 北京
OK
- 获取一个键值
127.0.0.1:6379> get address
"\xb1\xbe"
- 删除一个键值
127.0.0.1:6379> del address
(integer) 1
127.0.0.1:6379> get address
(nil)
注意:set 一个键值的时候,如果存在就相当于修改,不存在就是添加。
- 设置键秒值
setex key second value
127.0.0.1:6379> setex name 10 yiqi
OK
127.0.0.1:6379> get name
"yiqi"
127.0.0.1:6379> get name
"yiqi"
127.0.0.1:6379> get name
(nil)
- 同时设置/获取一个或多个 key-value 对
127.0.0.1:6379> mset key1 yiqi key2 seemi
OK
127.0.0.1:6379> mget key1 key2
1) "yiqi"
2) "seemi"
Hash(哈希)
测试案例
存放一个 user1 包含 name “smith” 、 age 30 、 job “golang coder”
127.0.0.1:6379> hset user1 name "smith"
(integer) 1
127.0.0.1:6379> hset user1 age 30
(integer) 1
127.0.0.1:6379> hset user1 job "golang coder"
(integer) 1
获取 user1
127.0.0.1:6379> hget user1 name
"smith"
127.0.0.1:6379> hget user1 age
"30"
127.0.0.1:6379> hget user1 job
"golang coder"
同时获取 user1
127.0.0.1:6379> hgetall user1
1) "name"
2) "smith"
3) "age"
4) "30"
5) "job"
6) "golang coder"
同时设置 / 获取 user2
127.0.0.1:6379> hmset user2 name jerry age 110 job "java coder"
OK
127.0.0.1:6379> hmget user2 name age job
1) "jerry"
2) "110"
3) "java coder"
统计一个hash有几个元素
127.0.0.1:6379> HLEN user1
(integer) 3
查看哈希表key中,给定字段是否存在
127.0.0.1:6379> HEXISTS user1 name
(integer) 1
127.0.0.1:6379> HEXISTS user1 name2
(integer) 0
List(列表)
存一个 city 包含三个城市(从左边插入)
127.0.0.1:6379> lpush city beijing shanghai tianjing
(integer) 3
存一个 heroList (从右边插入)
127.0.0.1:6379> rpush heroList aaa bbb ccc
(integer) 3
取值,但不改变原List
127.0.0.1:6379> lrange city 0 -1 ## -1 表示倒数第一个
1) "tianjing"
2) "shanghai"
3) "beijing"
取值,并弹出取走的值(从左边弹出)
127.0.0.1:6379> LPOP heroList
"aaa"
127.0.0.1:6379> LRANGE heroList 0 -1
1) "bbb"
2) "ccc"
取值,并弹出取走的值(从右边弹出)
127.0.0.1:6379> RPOP heroList
"ccc"
127.0.0.1:6379> LRANGE heroList 0 -1
1) "bbb"
删除 List
127.0.0.1:6379> DEL heroList
(integer) 1
127.0.0.1:6379> LRANGE heroList 0 -1
(empty list or set)
lindex ,按照索引下标获取元素
127.0.0.1:6379> LPUSH hero aaa bbb ccc
(integer) 3
127.0.0.1:6379> LINDEX hero 0
"ccc"
llen , 返回列表的长度
127.0.0.1:6379> LLEN hero
(integer) 3
Set(集合)
sadd
127.0.0.1:6379> sadd email yy@qq.com bb@qq.com
(integer) 2
smembers
127.0.0.1:6379> SMEMBERS email
1) "yy@qq.com"
2) "bb@qq.com"
sismember
127.0.0.1:6379> SISMEMBER email hh@qq.com
(integer) 1
127.0.0.1:6379> SISMEMBER email uu@qq.com
(integer) 0
srem
127.0.0.1:6379> srem email hh@qq.com
(integer) 1
127.0.0.1:6379> srem email hh@qq.com
(integer) 0