Redis五大数据类型之 Set 经常用到的命令


set中的值是不能重复的、无序的

1.SADD(添加元素)、SMEMBERS(查看set集合元素)
localhost:2>SADD myset "hello" #set集合中添加元素
"1"
localhost:2>SADD myset "world"
"1"
localhost:2>SMEMBERS myset  #查看set集合中的所有元素
1) "world"
2) "hello"
2.SISMEMBER(判断某个值在不在集合中)、SCARD(获取set集合中元素个数)
localhost:2>SISMEMBER myset hello
"1"
localhost:2>SISMEMBER myset world  #判断某个值在不在集合中 在返回1 不在返回0
"1"
localhost:2>SISMEMBER myset zhangsan
"0"
localhost:2>SCARD myset # 获取set集合中的内容元素个数
"2"

localhost:2>SMEMBERS myset
1) "world"
2) "hello"
3) "zhangsan"
3.SREM(移除set中的指定元素)、SRANDMEMBER(随机抽选出一个元素)、SPOP(随机删除一个元素)
localhost:2>SREM myset "zhangsan" #移除set中的指定元素
"1"
localhost:2>SMEMBERS myset
1) "world"
2) "hello"
localhost:2>SRANDMEMBER myset  #随机抽选出一个元素
"hello"
localhost:2>SRANDMEMBER myset
"world"
localhost:2>SMEMBERS myset
1) "world"
2) "orange"
3) "hello"
4) "pink"
5) "lightblue"
localhost:2>spop myset  #随机删除一个元素
"orange"
localhost:2>SMEMBERS myset
1) "hello"
2) "pink"
3) "world"
4) "lightblue"

4.SMOVE(将一个指定的值,移动到另外一个set集合)
localhost:2>SMEMBERS myset
1) "hello"
2) "pink"
3) "world"
4) "lightblue"
localhost:2>sadd myset2 "zhangsan"
"1"
localhost:2>SMOVE myset myset2 "hello" #将一个指定的值,移动到另外一个set集合
"1"
localhost:2>SMEMBERS myset2
1) "hello"
2) "zhangsan"
5.差集(SDIFF)、交集(SINTER)、并集(SUNION)
localhost:2>sadd key1 a
"1"
localhost:2>sadd key1 b
"1"
localhost:2>sadd key1 c
"1"
localhost:2>sadd key2 c
"1"
localhost:2>sadd key2 d
"1"
localhost:2>sadd key2 e
"1"
localhost:2>SDIFF key1 key2 #差集
1) "b"
2) "a"
localhost:2>SINTER key1 key2 #交集 共同好友就是这么实现的
1) "c"
localhost:2>SUNION key1 key2 #并集
1) "a"
2) "c"
3) "b"
4) "e"
5) "d"

微博、抖音将所有关注的人放在一个set集合中,将他的粉丝也放在一个集合中
共同关注、推荐好友都可以用set来实现

我是听狂神的课并进行记录。狂神说的非常好,大家快去学狂神说Java

猜你喜欢

转载自blog.csdn.net/weixin_43484014/article/details/117424239