替换redis设置值的最佳方法

时间:2019-05-29 14:36:23

标签: redis set

我想将键值类型的数据存储到Redis中,值是一种设置类型,这意味着没有重复值。我这样操作redis:

127.0.0.1:6379> sadd a 1 2 3
(integer) 3
127.0.0.1:6379> smembers a
1) "1"
2) "2"
3) "3"
127.0.0.1:6379> sadd a 4 5 6
(integer) 3
127.0.0.1:6379> smembers a
1) "3"
2) "2"
3) "4"
4) "5,"
5) "1"
6) "6"

我希望用户set(4,5,6)替换set(1,2,3)。

1 个答案:

答案 0 :(得分:4)

您的问题不明确。

如果您打算替换所有成员:

# Setup "a" with 3 members
127.0.0.1:6379> del a
(integer) 1
127.0.0.1:6379> sadd a 1 2 3
(integer) 3

# Actions - delete entire set and add 3 new members in one go
127.0.0.1:6379> multi
OK
127.0.0.1:6379> del a
QUEUED
127.0.0.1:6379> sadd a 4 5 6
QUEUED
127.0.0.1:6379> exec
1) (integer) 1
2) (integer) 3
127.0.0.1:6379> smembers a
1) "4"
2) "5"
3) "6"

如果您打算仅替换特定个成员:

# Setup "a" with 4 members
127.0.0.1:6379> del a
(integer) 1
127.0.0.1:6379> sadd a 0 1 2 3
(integer) 4

# Actions - delete 3 specific members and add 3 more, leaving others unaffected
127.0.0.1:6379> multi
OK
127.0.0.1:6379> srem a 1 2 3
QUEUED
127.0.0.1:6379> sadd a 4 5 6
QUEUED
127.0.0.1:6379> exec
1) (integer) 3
2) (integer) 3
127.0.0.1:6379> smembers a
1) "0"
2) "4"
3) "5"
4) "6"
127.0.0.1:6379>