例如,我通过以下方式配置缓存:
public IgniteCache<String, Object> getOrCreateCache(String cacheName) {
Ignite ignite = Ignition.ignite();
CacheConfiguration<String, Object> cacheCfg = new CacheConfiguration<String, Object>(cacheName);
cacheCfg.setExpiryPolicyFactory(CreatedExpiryPolicy.factoryOf(new Duration(TimeUnit.SECONDS, 30)));
IgniteCache<String, Object> igniteCache = ignite.getOrCreateCache(cacheCfg);
return igniteCache;
}
现在,如果稍后我想从返回的 igniteCache 中找出过期策略的持续时间怎么办。我可以通过以下 hacky 方式做到这一点,但它很丑陋,而且不可能是正确的方式:
import javax.cache.configuration.Factory;
import javax.cache.expiry.CreatedExpiryPolicy;
import javax.cache.expiry.Duration;
import org.apache.ignite.IgniteCache;
import org.apache.ignite.configuration.CacheConfiguration;
public class IgniteCacheManager {
private IgniteCache<String, Object> igniteCache;
public IgniteCacheManager(IgniteCache<String, Object> igniteCache) {
this.igniteCache = igniteCache;
}
public long getTimeToLive() {
long timeToLive = 0;
CacheConfiguration configuration = igniteCache.getConfiguration(CacheConfiguration.class);
Factory factory = configuration.getExpiryPolicyFactory();
Object obj = factory.create();
if (obj instanceof CreatedExpiryPolicy) {
CreatedExpiryPolicy cep = (CreatedExpiryPolicy)obj;
Duration dur = cep.getExpiryForCreation();
timeToLive = dur.getDurationAmount();
}
return timeToLive;
}
}
我正在使用的 Apache Ignite 版本是 1.5.0.final
顺便说一句,在 Ehcache 中,我可以通过以下方式简单地获取配置:
import net.sf.ehcache.Cache;
import net.sf.ehcache.config.CacheConfiguration;
public class EhcacheCacheManager {
private Cache cache;
public EhcacheCacheManager(Cache cache) {
this.cache = cache;
}
public long getTimeToLive() {
long timeToLive = 0;
CacheConfiguration config = cache.getCacheConfiguration();
timeToLive = config.getTimeToLiveSeconds();
return timeToLive;
}
}