Redis 的 Set 是 String 类型的无序集合。集合成员是唯一的,这就意味着集合中不能出现重复的数据。
Redis 中集合是通过哈希表实现的,所以添加,删除,查找的复杂度都是 O(1)。
集合中最大的成员数为 232 - 1 (4294967295, 每个集合可存储40多亿个成员)。
实例:
redis 127.0.0.1:6379> SADD runoobkey redis
(integer) 1
redis 127.0.0.1:6379> SADD runoobkey mongodb
(integer) 1
redis 127.0.0.1:6379> SADD runoobkey mysql
(integer) 1
redis 127.0.0.1:6379> SADD runoobkey mysql
(integer) 0
redis 127.0.0.1:6379> SMEMBERS runoobkey
1) "mysql"
2) "mongodb"
3) "redis"
1.1、SADD
127.0.0.1:6379> sadd myset "hello" //set集合添加元素
(integer) 1
127.0.0.1:6379> sadd myset "lizhengi"
(integer) 1
127.0.0.1:6379> sadd myset "world"
(integer) 1
127.0.0.1:6379> SMEMBERS myset //查看指定set所有值
1) "world"
2) "lizhengi"
3) "hello"
127.0.0.1:6379> SISMEMBER myset hello //判断某个值是否在set中
(integer) 1
127.0.0.1:6379> SISMEMBER myset hh
(integer) 0
1.2、scard
127.0.0.1:6379> scard myset //获取set长度
(integer) 3
1.3、srem
127.0.0.1:6379> SMEMBERS myset
1) "world"
2) "lizhengi"
3) "hello"
127.0.0.1:6379> srem myset hello world //移除set集合中指定一些元素
(integer) 2
127.0.0.1:6379> scard myset
(integer) 1
127.0.0.1:6379> SMEMBERS myset
1) "lizhengi"
127.0.0.1:6379>
1.4、SRANDMEMBER
127.0.0.1:6379> SRANDMEMBER myset //随机抽出set集合的一个元素
"hello"
127.0.0.1:6379> SRANDMEMBER myset
"world"
127.0.0.1:6379>
1.5、SPOP
127.0.0.1:6379> SMEMBERS myset
1) "adsa"
2) "world"
3) "lizhengi"
4) "hello"
127.0.0.1:6379> SPOP myset //随机删除set集合某些元素
"lizhengi"
127.0.0.1:6379> SPOP myset
"hello"
127.0.0.1:6379> SMEMBERS myset
1) "adsa"
2) "world"
127.0.0.1:6379>
1.6、SMOVE
127.0.0.1:6379> SMEMBERS myset
1) "adsa"
2) "world"
127.0.0.1:6379> sadd myset2 "adsa"
(integer) 1
127.0.0.1:6379> SMEMBERS myset
1) "adsa"
2) "world"
127.0.0.1:6379> SMEMBERS myset2
1) "adsa"
127.0.0.1:6379> SMOVE myset myset2 "world" //移动指定元素到另外一个集合
(integer) 1
127.0.0.1:6379> SMEMBERS myset
1) "adsa"
127.0.0.1:6379> SMEMBERS myset2
1) "adsa"
2) "world"
127.0.0.1:6379>
1.7、SDIFF 、SINTER、SUNION
127.0.0.1:6379> SMEMBERS myset
1) "adsa"
2) "aadsa"
127.0.0.1:6379> SMEMBERS myset2
1) "adsa"
2) "world"
127.0.0.1:6379> SDIFF myset myset2 //差集
1) "aadsa"
127.0.0.1:6379> SINTER myset myset2 //交集
1) "adsa"
127.0.0.1:6379> SUNION myset myset2 //并集
1) "adsa"
2) "world"
3) "aadsa"