技术开发 频道

Redis入门教程:特性及数据类型的操作

  3、集合(Sets)类型

  Redis能够将一系列不重复的值存储成一个集合:

  redis 127.0.0.1:6379> SADD birds crow

  (
integer) 1

  redis
127.0.0.1:6379> SADD birds pigeon

  (
integer) 1

  redis
127.0.0.1:6379> SADD birds bat

  (
integer) 1

  redis
127.0.0.1:6379> SADD mammals dog

  (
integer) 1

  redis
127.0.0.1:6379> SADD mammals cat

  (
integer) 1

  redis
127.0.0.1:6379> SADD mammals bat

  (
integer) 1

  redis
127.0.0.1:6379> SMEMBERS birds

  
1) "bat"

  
2) "crow"

  
3) "pigeon"

  redis
127.0.0.1:6379> SMEMBERS mammals

  
1) "bat"

  
2) "cat"

  
3) "dog"

  Sets结构也支持相应的修改操作:

  redis 127.0.0.1:6379> SREM mammals cat

  (
integer) 1

  redis
127.0.0.1:6379> SMEMBERS mammals

  
1) "bat"

  
2) "dog"

  redis
127.0.0.1:6379> SADD mammals human

  (
integer) 1

  redis
127.0.0.1:6379> SMEMBERS mammals

  
1) "bat"

  
2) "human"

  
3) "dog"

  Redis还支持对集合的子交并补等操作:

  redis 127.0.0.1:6379> SINTER birds mammals

  
1) "bat"

  redis
127.0.0.1:6379> SUNION birds mammals

  
1) "crow"

  
2) "bat"

  
3) "human"

  
4) "pigeon"

  
5) "dog"

  redis
127.0.0.1:6379> SDIFF birds mammals

  
1) "crow"

  
2) "pigeon"

  4、有序集合(Sorted Sets)类型

  Sorted Sets和Sets结构相似,不同的是存在Sorted Sets中的数据会有一个score属性,并会在写入时就按这个score排好序。

  redis 127.0.0.1:6379> ZADD days 0 mon

  (
integer) 1

  redis
127.0.0.1:6379> ZADD days 1 tue

  (
integer) 1

  redis
127.0.0.1:6379> ZADD days 2 wed

  (
integer) 1

  redis
127.0.0.1:6379> ZADD days 3 thu

  (
integer) 1

  redis
127.0.0.1:6379> ZADD days 4 fri

  (
integer) 1

  redis
127.0.0.1:6379> ZADD days 5 sat

  (
integer) 1

  redis
127.0.0.1:6379> ZADD days 6 sun

  (
integer) 1

  redis
127.0.0.1:6379> ZCARD days

  (
integer) 7

  redis
127.0.0.1:6379> ZRANGE days 0 6

  
1) "mon"

  
2) "tue"

  
3) "wed"

  
4) "thu"

  
5) "fri"

  
6) "sat"

  
7) "sun"

  redis
127.0.0.1:6379> ZSCORE days sat

  "
5"

  redis
127.0.0.1:6379> ZCOUNT days 3 6

  (
integer) 4

  redis
127.0.0.1:6379> ZRANGEBYSCORE days 3 6

  
1) "thu"

  
2) "fri"

  
3) "sat"

  
4) "sun"

  5、Hash类型

  Redis能够存储key对多个属性的数据(比如user1.uname user1.passwd)

  redis 127.0.0.1:6379> HKEYS student

  
1) "name"

  
2) "age"

  
3) "sex"

  redis
127.0.0.1:6379> HVALS student

  
1) "Ganesh"

  
2) "30"

  
3) "Male"

  redis
127.0.0.1:6379> HGETALL student

  
1) "name"

  
2) "Ganesh"

  
3) "age"

  
4) "30"

  
5) "sex"

  
6) "Male"

  redis
127.0.0.1:6379> HDEL student sex

  (
integer) 1

  redis
127.0.0.1:6379> HGETALL student

  
1) "name"

  
2) "Ganesh"

  
3) "age"

  
4) "30"

  Hash数据结构能够批量修改和获取

  redis 127.0.0.1:6379> HMSET kid name Akshi age 2 sex Female

  OK

  redis
127.0.0.1:6379> HMGET kid name age sex

  
1) "Akshi"

  
2) "2"

  
3) "Female"

  
3.Publish/Subscribe

  Redis支持这样一种特性,你可以将数据推到某个信息管道中,然后其它人可以通过订阅这些管道来获取推送过来的信息。

2
相关文章