Hazelcast IMap固定时长驱逐条目咨询(不受更新影响)
Hey there! Let's break down exactly how to meet your requirement where IMap entries get evicted after a fixed duration regardless of how many times they're updated — this is totally doable with Hazelcast's built-in configuration.
核心配置:time-to-live-seconds
First off, you're already on the right track with the time-to-live-seconds setting. As per Hazelcast's docs, this config defines the maximum time (in seconds) an entry stays in the map counting from its initial creation time. Crucially, any subsequent updates to the entry won't reset this timer — exactly what you need for your use case (e.g., an entry added on May 12 gets evicted on May 26, no matter how many times you update it in between).
具体配置示例
Below are examples for both XML and programmatic Java configurations, using 14 days (1209600 seconds) as your desired TTL:
XML Configuration
<hazelcast> <map name="your-target-map"> <!-- 14 days = 14 * 24 * 60 * 60 = 1209600 seconds --> <time-to-live-seconds>1209600</time-to-live-seconds> <!-- Optional: Configure eviction for proactive cleanup --> <eviction-policy>LRU</eviction-policy> <eviction-check-interval-seconds>30</eviction-check-interval-seconds> </map> </hazelcast>
Programmatic Java Configuration
import com.hazelcast.config.Config; import com.hazelcast.config.MapConfig; import com.hazelcast.core.Hazelcast; import com.hazelcast.core.HazelcastInstance; import com.hazelcast.core.IMap; import com.hazelcast.config.EvictionPolicy; public class HazelcastMapTTLSetup { public static void main(String[] args) { Config config = new Config(); MapConfig mapConfig = config.getMapConfig("your-target-map"); // Set TTL to 14 days in seconds mapConfig.setTimeToLiveSeconds(14 * 24 * 60 * 60); // Optional: Proactive eviction settings mapConfig.setEvictionPolicy(EvictionPolicy.LRU); mapConfig.setEvictionCheckIntervalSeconds(30); HazelcastInstance hazelcastInstance = Hazelcast.newHazelcastInstance(config); IMap<String, YourCustomObject> yourMap = hazelcastInstance.getMap("your-target-map"); // Usage example: Add an entry that will expire in 14 days yourMap.put("user123", new YourCustomObject()); } }
Key Notes to Remember
- No TTL reset on updates: The
time-to-live-secondstimer starts when the entry is first added. Calls toput(),set(), or other update methods won't extend or reset this timer — perfect for your scenario. - Per-entry TTL override: If you need some entries to have a different fixed duration, you can specify the TTL directly when putting the entry:
yourMap.put("special-key", specialValue, 86400, TimeUnit.SECONDS); // Expires in 1 day instead of 14 - Eviction cleanup: Hazelcast uses lazy eviction by default (checks if an entry is expired when you access it). Adding
eviction-check-interval-secondsenables periodic background checks to clean up expired entries proactively, which helps keep memory usage in check.
内容的提问来源于stack exchange,提问作者Indraneel Bende

