将 ttl 设置为 Imap

Set ttl to Imap

我在 hazelcast (key, value) 中有一个 IMap,在 imap.put() 时没有设置 ttl。现在,在触发事件后,我想将 ttl 设置为 IMap 中的这个特定键。因为,在此事件发生时,我不想先调用 value = imap.get(key) 然后再调用 imap.put(key, value, 10, TimeUnit.SECONDS) 。 那么如何将 ttl 设置为该特定密钥?

除了使用 IMap 方法之外,没有直接的方法可以做到这一点。但是,我想知道避免以下调用的原因。

value = imap.get(key);
imap.put(key, value, 10, TimeUnit.SECONDS)

如果您还想达到这个效果,可以采用以下方法之一。

  1. 如果您已经有价值,请致电imap.set(key, value, 10, TimeUnit.SECONDS)imap.set()imap.put() 更有效,因为它不是 return 旧值。

  2. 如果可以容纳多用一张IMap:多用一张地图ttlMap<key, Boolean>。每当您需要为实际 imap 中的条目设置 ttl 值时,请在 ttlMap.set(key, true, 10, TimeUnit.SECONDS); 中设置条目。现在,使用 addEntryListener() 方法将 MapListener 添加到 ttlMap。每当 ttlMap 中的条目被逐出时, entryEvicted(EntryEvent<String, String> arg0) 方法将被调用。从该方法中的实际 imap 中逐出您的条目。

  3. 如果您准备亲自动手,可以修改源代码,使 EntryProcessor 方法的 process() 方法将接收自定义 Map.Entry 使用新方法设置密钥的 ttlValue。

希望这对您有所帮助。

从版本 3.11 开始,Hazelcast IMapsetTtl(K key,long ttl, TimeUnit timeunit) 方法可以做到这一点:

Updates TTL (time to live) value of the entry specified by key with a new TTL value. New TTL value is valid starting from the time this operation is invoked, not since the time the entry was created. If the entry does not exist or is already expired, this call has no effect.