2.Redis的数据类型

 

Redis的数据类型

Redis支持五种数据类型:

1. string(字符串)

1
2
3
4
5
6
127.0.0.1:6379> SET maxLength 100
OK
127.0.0.1:6379> GET maxLength
"100"
127.0.0.1:6379> GET maxlength
(nil)

2. hash(哈希)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
127.0.0.1:6379> HMSET student name "Danny" age 20 score 90
OK
127.0.0.1:6379> HLEN student
(integer) 3
127.0.0.1:6379> HKEYS key
(empty list or set)
127.0.0.1:6379> HKEYS student
1) "name"
2) "age"
3) "score"
127.0.0.1:6379> HKEYS student name score
(error) ERR wrong number of arguments for 'hkeys' command
127.0.0.1:6379> HMGET student name score
1) "Danny"
2) "90"
127.0.0.1:6379> HGETALL student
1) "name"
2) "Danny"
3) "age"
4) "20"
5) "score"
6) "90"
127.0.0.1:6379> HGET student age
"20"
127.0.0.1:6379> HVALS student
1) "Danny"
2) "20"
3) "90"
127.0.0.1:6379>

3. list(列表)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
127.0.0.1:6379> LPUSH subject math
(integer) 1
127.0.0.1:6379> LPUSH subject geography
(integer) 2
127.0.0.1:6379> LPUSH subject chemistry
(integer) 3
127.0.0.1:6379> LLEN subject
(integer) 3
127.0.0.1:6379> LINDEX subject 0
"chemistry"
127.0.0.1:6379> LRANGE subject 0 10
1) "chemistry"
2) "geography"
3) "math"
127.0.0.1:6379>

4. set(集合)

Redis 的 Set 是 String 类型的无序集合。集合成员是唯一的,这就意味着集合中不能出现重复的数据。

Redis 中集合是通过哈希表实现的,所以添加,删除,查找的复杂度都是 O(1)。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
127.0.0.1:6379> SADD score 60
(integer) 1
127.0.0.1:6379> SADD score 80
(integer) 1
127.0.0.1:6379> SADD score 100
(integer) 1
127.0.0.1:6379> SADD score 90
(integer) 1
127.0.0.1:6379> SADD score 95
(integer) 1
127.0.0.1:6379> SMEMBERS score
1) "60"
2) "80"
3) "90"
4) "95"
5) "100"
127.0.0.1:6379> SCARD score
(integer) 5
127.0.0.1:6379> SISMEMBER score 90
(integer) 1
127.0.0.1:6379> SISMEMBER score 70
(integer) 0
127.0.0.1:6379>

5. zset(sorted set:有序集合)。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
127.0.0.1:6379> ZADD level 1 low
(integer) 1
127.0.0.1:6379> ZADD level 2 middle
(integer) 1
127.0.0.1:6379> ZADD level 3 high
(integer) 1
127.0.0.1:6379> ZRANGE level 0 10 WITHSCORES
1) "low"
2) "1"
3) "middle"
4) "2"
5) "high"
6) "3"
127.0.0.1:6379> ZRANGE level 0 10
1) "low"
2) "middle"
3) "high"
127.0.0.1:6379>