为Redis中的Hashmap值设置过期时间

为Redis中的Hashmap值设置过期时间

本文介绍了为Redis中的Hashmap值设置过期时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何像使用 SETX 为常规值设置 Redis 中的哈希映射一样设置到期时间.我想为我为其存储 hasmap 的会话提供 TTL.我可以使用 SETEX 本身创建一个 Hashmap 吗?

How do I set expiry for hashmaps in Redis like I do for regular values using SETX.I want to provide TTL for a session for which I am storing a hasmap.Can I create a Hashmap using SETEX itself ?

推荐答案

不,你不能用 SETEX(它是一个字符串方法)创建哈希.您可以对散列键调用 EXPIRE ,但这将使整个散列过期.目前不支持单个哈希键/值对过期.

No, you can't create hash with SETEX (which is a strings methods). You can call EXPIRE on hash key, but that will expire the whole hash. There's no support at the moment for expiration of individual hash key/value pairs.

如果您想在设置单个元素的同时设置整个哈希的过期时间,可以通过多种方式实现.

If you wanted to set expiration on the whole hash while setting its individual elements, you can achieve that in several ways.

  1. 使用流水线.流水线是一种特殊的操作模式,redis 客户端快速连续地发出几个命令,而不是等待回复发送下一个.这是 ruby​​ 中的一个示例:

  1. Use pipelining. Pipelining is a special mode of operation where redis client issues several commands in quick succession, not waiting for a reply to send next one. Here's an example in ruby:

redis.pipelined do
  redis.hset "foo", "bar", 1
  redis.expire "foo", 300
end

  • 使用事务.没有被监视的键​​,这类似于流水线操作(因为事务不能中止).保证命令一起运行并以原子方式运行(多个管道可以交错运行,事务被序列化)

  • Use transactions. Without watched keys this is similar to pipelining (for a transaction can't abort). The commands are guaranteed to run together and atomically (several pipelines can run interleaved, transactions are serialized)

    redis.multi do
      redis.hset "foo", "bar", 1
      redis.expire "foo", 300
    end
    

  • 使用 lua 脚本来实现您的自定义 HSETEX 命令.它将以原子方式执行,您只需发送一个命令(而不是 2(流水线)或 4(事务)).

  • Use lua scripting to implement your custom HSETEX command. It will be executed atomically and you just have to send one command (instead of 2(pipelining) or 4 (transaction)).

    这篇关于为Redis中的Hashmap值设置过期时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

  • 08-07 04:19