未根据<time-to-live-seconds>



我们将<time-to-live-seconds>配置为1200(20分钟(,但缓存创建时间一分钟后会自动收回。

有人能告诉我们如何让缓存在指定的时间段内有效吗?

hazelcast.xml中的以下代码段将"simpleMap"中的条目的time-to-live-seconds属性设置为150秒。超过150秒且在150秒内未更新的条目将自动从地图中逐出。

<map name="simpleMap">
    <backup-count>0</backup-count>
    <max-idle-seconds>0</max-idle-seconds>
    <eviction-policy>LRU</eviction-policy>
    <time-to-live-seconds>30</time-to-live-seconds>
    <max-size>3000</max-size>
    <eviction-percentage>30</eviction-percentage>
    <merge-policy>com.hazelcast.map.merge.PutIfAbsentMapMergePolicy</merge-policy>
</map>

出于测试目的,我在"simpleMap"上附加了一个条目侦听器(如果使用ver3.5,请使用MapListener接口(,每当从映射中逐出条目时,它都会打印键和值。

public static void main(String[] args) 
{
    HazelcastInstance instance = HazelcastHelper.getHazelcastInstance();
    IMap<String, String> map = instance.getMap("simpleMap");
    map.addEntryListener(new SimpleMapEntryListener(), true);
    map.put("evictme", "value");
    printTime();
    try {
        Thread.sleep(1000 * 60);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    printTime();
}
private static void printTime()
{
    Calendar cal = Calendar.getInstance();
    SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
    System.out.println( sdf.format(cal.getTime()) );
}
class SimpleMapEntryListener implements EntryListener<String, String>
{
    @Override
    public void entryEvicted(EntryEvent<String, String> arg0) 
    {
        System.out.println("Key : " + arg0.getKey() + " Value: " + arg0.getOldValue() + " evicted.");
        // print current time here.
    }
    // Add other overriden methods.
}

如果你执行上面给出的代码,你可以看到条目<"驱逐我","value">仅在30秒后自动驱逐。

您可能还需要检查max-idle-seconds配置(请参阅上面的示例,它被设置为零,这意味着无限(。如果设置了缓存(即不为零(,缓存将根据max-idle-seconds被逐出。

最新更新