redis 以原子方式切换值

redis switch values atomically

我必须要有一些东西(可能是一个列表,排序集,也许是一个简单的字符串) 包含各种数字(不重复),我需要能够切换一些

例如列表:

LRANGE todo:20 0 -1 => "2" "5" "6" "7"

做我的转换:即

MULTI

LRANGE todo:20 0 1 => "2" "5" (store them)
LSET todo:20 0 "5"
LSET todo:20 1 "2"

EXEC

最终结果:

LRANGE todo:20 0 -1 => "5" "2" "6" "7"

有什么方法可以让我以更简单(或更好)的方式做到这一点,或者是 "limitation" 的 REDIS?

您可以编写一个 Lua 脚本来执行此操作,然后调用它来代替您的交易。您也可以使用模块,但如果请求很简单,那可能就有点矫枉过正了。

您可以使用SORT命令。

将这些索引存储在 SET 中,并为每个索引存储相应的 score/weight,并按它排序。分数键可以是一个哈希值,你可以有很多不同的分数集。

举个例子: 一个有 3 个参数的待办事项列表,插入时间、执行时间和优先级。

127.0.0.1:6379> SADD todos 1 2 3
127.0.0.1:6379> HMSET todos:1 insertionTime 1 executionTime 10 priority 5
127.0.0.1:6379> HMSET todos:2 insertionTime 2 executionTime 25 priority 1
127.0.0.1:6379> HMSET todos:3 insertionTime 5 executionTime 4 priority 7

要获得按每个排序的列表:

127.0.0.1:6379> SORT todos by todos:*->insertionTime
1) "1"
2) "2"
3) "3"
127.0.0.1:6379> SORT todos by todos:*->executionTime
1) "3"
2) "1"
3) "2"
127.0.0.1:6379> SORT todos by todos:*->priority
1) "2"
2) "1"
3) "3"

如果您还将任务本身(或任何其他数据)保存在此哈希或同一 Redis 数据库中的任何其他键中,您可以使用可选的 GET 参数在同一个调用中获取它:

127.0.0.1:6379> HSET todos:1 task "do something"
127.0.0.1:6379> HSET todos:2 task "do something else"
127.0.0.1:6379> HSET todos:3 task "do this other thing"

127.0.0.1:6379> SORT todos by todos:*->priority get todos:*->task
1) "do something else"
2) "do something"
3) "do this other thing"

请注意,SORT 命令不适用于 Redis 集群,因为您正在访问多个键。而且这个命令的时间复杂度可能非常高,你应该谨慎使用它,尤其是当使用量和设置大小按比例增加时。