【问题标题】:How to combine Redis commands 'expire' and 'sadd' into one command?如何将 Redis 命令 'expire' 和 'sadd' 组合成一个命令?
【发布时间】:2020-06-26 02:35:57
【问题描述】:

我需要在 Redis 中创建一个集合:

redis> SADD myset "Hello"
(integer) 1
redis> SADD myset "World"
(integer) 1
redis> SADD myset "World"
(integer) 0
redis> SMEMBERS myset
1) "World"
2) "Hello"

但是我需要为密钥myset设置过期时间。

换句话说,我需要一个expire sadd myset... 类型的命令(例如用于字符串值的 SETEX)。

有没有办法在对 Redis 服务器的每个请求中执行这些命令?

【问题讨论】:

    标签: redis


    【解决方案1】:

    没有内置命令可以执行此操作。你可以做的是;使用事务。正如documentation中所述;

    事务中的所有命令都被序列化并按顺序执行。在 Redis 事务的执行过程中服务于另一个客户端发出的请求永远不会发生。这保证了命令作为单个独立操作执行。

    127.0.0.1:6379> MULTI
    OK
    127.0.0.1:6379> SADD mynewset a b c d e f g
    QUEUED
    127.0.0.1:6379> SADD mynewset f g h j k l
    QUEUED
    127.0.0.1:6379> EXPIRE mynewset 86400
    QUEUED
    127.0.0.1:6379> EXEC
    1) (integer) 7
    2) (integer) 4
    3) (integer) 1
    127.0.0.1:6379> TTL mynewset
    (integer) 86394
    127.0.0.1:6379>
    

    【讨论】:

      【解决方案2】:

      还可以使用 Lua 脚本将两个命令绑定在一起:

      127.0.0.1:6379> EVAL "redis.call('SADD', KEYS[1], unpack(ARGV)) redis.call('EXPIRE', KEYS[1], 3600)" 1 myset a b c d e
      (nil)
      127.0.0.1:6379> SMEMBERS myset
      1) "c"
      2) "d"
      3) "a"
      4) "b"
      5) "e"
      127.0.0.1:6379> TTL myset
      (integer) 3596
      

      【讨论】:

        猜你喜欢
        • 2022-01-08
        • 1970-01-01
        • 1970-01-01
        • 2014-01-10
        • 2016-11-20
        • 2015-04-20
        • 2017-01-01
        • 1970-01-01
        • 2020-08-07
        相关资源
        最近更新 更多