代码之家  ›  专栏  ›  技术社区  ›  Jérôme B

redis自动切换值

  •  0
  • Jérôme B  · 技术社区  · 7 年前

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

    例如,列表:

    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的“局限性”?

    2 回复  |  直到 7 年前
        1
  •  1
  •   Ofir Luzon    7 年前

    您可以使用 SORT

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

    举个例子:

    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"
    

        2
  •  0
  •   Chris Tanner    7 年前

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