List redis以原子方式切换值

List redis以原子方式切换值,list,redis,transactions,atomic,sortedset,List,Redis,Transactions,Atomic,Sortedset,我必须有一些东西(可能是一个列表,排序集,可能是一个简单的字符串) 包含各种数字(非重复),我需要能够切换一些 例如,使用列表: 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"

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

例如,使用列表:

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"

我有没有办法用一种更简单(或更好)的方式来做这件事,或者这是REDIS的一个“限制”?

您可以编写一个Lua脚本来做这件事,然后调用它来代替您的事务。您也可以使用模块,但如果请求很简单,那么这可能会有点过分。

您可以使用
排序
命令

将这些索引存储在
集合中,并为每个索引存储相应的分数/权重,并按其排序。分数键可以是散列,并且可以有许多不同的分数集

下面是一个例子: 包含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 db中,则可以使用可选的
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 cluster,因为您正在访问多个键。而且这个命令时间复杂度可能非常高,您应该谨慎使用它,尤其是在使用和设置规模扩大时