list - redis 以原子方式切换值

标签 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" "2" "6" "7"

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

最佳答案

您可以使用SORT 命令。

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

举个例子: 一个包含 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 集群,因为您正在访问多个键。而且这个命令的时间复杂度可能非常高,你应该谨慎使用它,尤其是当使用量和集合大小按比例增加时。

关于list - redis 以原子方式切换值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46548758/

相关文章:

redis - 检查列表中是否已经存在值 Redis

java - 数据库驱动程序需要支持分布式事务还是数据库本身需要支持?

c - C中的嵌套合并排序不起作用

python - 如何在 python 中将列表折叠成字符串?

java - Redis hmget 超时时间

asp.net-core - 在启动期间注册 OpenTelemetry 并在运行时动态添加更多功能

c# - MySQL 和事务不回滚

php - 在 MySQLi 中使用 "begin_transaction"方法有什么好处?

Python 列表帮助,列表中没有重复项

python - 如何在python中将列表列表转换为数据框