net.sf.ehcache.Cache类的使用及代码示例

x33g5p2x  于2022-01-18 转载在 其他  
字(10.9k)|赞(0)|评价(0)|浏览(495)

本文整理了Java中net.sf.ehcache.Cache类的一些代码示例,展示了Cache类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Cache类的具体详情如下:
包路径:net.sf.ehcache.Cache
类名称:Cache

Cache介绍

[英]Cache is the central class in ehcache. Caches have Elements and are managed by the CacheManager. The Cache performs logical actions. It delegates physical implementations to its net.sf.ehcache.store.Stores.

A reference to a Cache can be obtained through the CacheManager. A Cache thus obtained is guaranteed to have status Status#STATUS_ALIVE. This status is checked for any method which throws IllegalStateException and the same thrown if it is not alive. This would normally happen if a call is made after CacheManager#shutdown is invoked.

Cache is threadsafe.

Statistics on cache usage are collected and made available through the #getStatistics() methods.

Various decorators are available for Cache, such as BlockingCache, SelfPopulatingCache and the dynamic proxy ExceptionHandlingDynamicCacheProxy. See each class for details.
[中]Cache是ehcache中的中心类。缓存有元素,由CacheManager管理。缓存执行逻辑操作。它将物理实现委托给它的网络。旧金山。ehcache。百货商店商店。
可以通过CacheManager获得对缓存的引用。这样获得的缓存保证具有status status#status_ALIVE。对于引发IllegalStateException的任何方法,都会检查此状态,如果该方法不处于活动状态,则会引发相同的异常。如果在调用CacheManager#shutdown后调用,通常会发生这种情况。
缓存是线程安全的。
通过#getStatistics()方法收集并提供有关缓存使用情况的统计信息。
缓存可以使用各种装饰器,例如BlockingCache、SelfPopulatingCache和DynamicProxy ExceptionHandlingDynamicCacheProxy。有关详细信息,请参见每个类。

代码示例

代码示例来源:origin: ninjaframework/ninja

public synchronized long incr(String key, int by) {
  Element e = ehCache.get(key);
  if (e == null) {
    return -1;
  }
  long newValue = ((Number) e.getObjectValue()).longValue() + by;
  Element newE = new Element(key, newValue);
  newE.setTimeToLive(e.getTimeToLive());
  ehCache.put(newE);
  return newValue;
}

代码示例来源:origin: BroadleafCommerce/BroadleafCommerce

@Override
public Boolean removeURLHandlerFromCache(String mapKey) {
  Boolean success = Boolean.FALSE;
  if (mapKey != null) {
    Element e = getUrlHandlerCache().get(mapKey);
    if (e != null && e.getObjectValue() != null) {
      success = Boolean.valueOf(getUrlHandlerCache().remove(mapKey));
    }
  }
  return success;
}

代码示例来源:origin: javamelody/javamelody

private void clearCache(String cacheId) {
  final List<CacheManager> allCacheManagers = CacheManager.ALL_CACHE_MANAGERS;
  for (final CacheManager cacheManager : allCacheManagers) {
    final Cache cache = cacheManager.getCache(cacheId);
    if (cache != null) {
      cache.removeAll();
    }
  }
}

代码示例来源:origin: ninjaframework/ninja

public void add(String key, Object value, int expiration) {
  if (ehCache.get(key) != null) {
    return;
  }
  Element element = new Element(key, value);
  element.setTimeToLive(expiration);
  ehCache.put(element);
}

代码示例来源:origin: javamelody/javamelody

private void clearCacheKey(String cacheId, String cacheKey) {
  final List<CacheManager> allCacheManagers = CacheManager.ALL_CACHE_MANAGERS;
  for (final CacheManager cacheManager : allCacheManagers) {
    final Cache cache = cacheManager.getCache(cacheId);
    if (cache != null) {
      final boolean removed = cache.remove(cacheKey);
      if (!removed) {
        // if keys are not Strings, we have to find the initial key
        for (final Object key : cache.getKeys()) {
          if (key != null && key.toString().equals(cacheKey)) {
            cache.remove(key);
            break;
          }
        }
      }
    }
  }
}

代码示例来源:origin: Dreampie/Resty

public void addCache(String group, String key, Object cache, int expired) {
 createIfMissing(group);
 Element element;
 if (expired != -1) {
  element = new Element(key, cache, false, expired, expired);
 } else {
  element = new Element(key, cache);
 }
 cacheManager.getCache(group).put(element);
}

代码示例来源:origin: net.sf.ehcache/ehcache

Element element = get(key);
if (element != null) {
  return element;
  element = getQuiet(key);
  if (element != null) {
    return element;
  long cacheLoaderTimeoutMillis = configuration.getCacheLoaderTimeoutMillis();
  final Object value;
  if (cacheLoaderTimeoutMillis > 0) {
    final Future<AtomicReference<Object>> future = asynchronousLoad(key, loader, loaderArgument);
    value = future.get(cacheLoaderTimeoutMillis, TimeUnit.MILLISECONDS).get();
  } else {
    value = loadValueUsingLoader(key, loader, loaderArgument);
    return getQuiet(key);
  } else {
    Element newElement = new Element(key, value);
    put(newElement, false);
    Element fromCache = getQuiet(key);
    if (fromCache == null) {
      return newElement;
  throw new LoaderTimeoutException("Timeout on load for key " + key, e);
} catch (Exception e) {
  throw new CacheException("Exception on load for key " + key, e);

代码示例来源:origin: apache/kylin

System.out.println("runtime used memory: " + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / 1024 / 1024 + "M");
    new Cache(new CacheConfiguration("test", 0).//
        memoryStoreEvictionPolicy(MemoryStoreEvictionPolicy.LRU).//
        eternal(false).//
        timeToIdleSeconds(86400).//
testCache.put(new Element("1", blob));
System.out.println(testCache.get("1") == null);
System.out.println(testCache.getSize());
System.out.println(testCache.getStatistics().getLocalHeapSizeInBytes());
System.out.println("runtime used memory: " + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / 1024 / 1024 + "M");
testCache.put(new Element("2", blob));
System.out.println(testCache.get("1") == null);
System.out.println(testCache.get("2") == null);
System.out.println(testCache.getSize());
System.out.println(testCache.getStatistics().getLocalHeapSizeInBytes());
System.out.println("runtime used memory: " + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / 1024 / 1024 + "M");
testCache.put(new Element("3", blob));
System.out.println(testCache.get("1") == null);
System.out.println(testCache.get("2") == null);
System.out.println(testCache.get("3") == null);
System.out.println(testCache.getSize());
System.out.println(testCache.getStatistics().getLocalHeapSizeInBytes());
System.out.println("runtime used memory: " + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / 1024 / 1024 + "M");

代码示例来源:origin: banq/jdonframework

/**
 * ehcache不支持putIfAbsent原子操作
 */
@Override
public synchronized Object putIfAbsent(Object key, Object value) {		
  Cache cache = manager.getCache(ehcacheConf.getPredefinedCacheName());
  if (!cache.isKeyInCache(key)){
    Element element = new Element(key, value);
    cache.put(element);
  }
  Element e = (Element)cache.get(key);
  return e.getObjectValue();
}

代码示例来源:origin: net.sf.ehcache/ehcache

/**
   * Calls the CacheLoader and puts the result in the Cache
   */
  public void run() throws CacheException {
    try {
      //Test to see if it has turned up in the meantime
      boolean existsOnRun = isKeyInCache(key);
      if (!existsOnRun) {
        Object value = loadValueUsingLoader(key, specificLoader, argument);
        if (value != null) {
          put(new Element(key, value), false);
        }
      }
    } catch (RuntimeException e) {
      if (LOG.isDebugEnabled()) {
        LOG.debug("Problem during load. Load will not be completed. Cause was " + e.getCause(), e);
      }
      throw new CacheException("Problem during load. Load will not be completed. Cause was " + e.getCause(), e);
    }
  }
});

代码示例来源:origin: Dreampie/Resty

public <T> T getCache(String group, String key) {
 try {
  createIfMissing(group);
  Cache c = cacheManager.getCache(group);
  return (T) (c.get(key) == null ? null : c.get(key).getObjectValue());
 } catch (Exception e) {
  logger.warn("%s", e, e);
  return null;
 }
}

代码示例来源:origin: nschlimm/playground

public static void main(String[] args) throws CacheException, FileNotFoundException {
    CacheManager mgr = CacheManager.newInstance();
    System.out.println(mgr.getConfiguration().getCacheConfigurations().toString());
    Cache cache = mgr.getCache("sampleCache1");
    cache.put(new Element("Frank", "Groer Junge!"));
    System.out.println(cache.get("Frank"));
    mgr.shutdown();
  }
}

代码示例来源:origin: gravitee-io/gravitee-gateway

@Bean
public Cache cache() {
  CacheManager cacheManager = cacheManager();
  Cache apiKeyCache = cacheManager.getCache(CACHE_NAME);
  if (apiKeyCache == null) {
    LOGGER.warn("EHCache cache for " + CACHE_NAME + " not found. Fallback to default EHCache configuration");
    CacheConfiguration cacheConfiguration = new CacheConfiguration(CACHE_NAME, 1000);
    cacheManager.addCache(new Cache(cacheConfiguration));
  }
  return cacheManager.getCache(CACHE_NAME);
}

代码示例来源:origin: shuzheng/zheng

/**
 * 新增缓存记录
 * @param cacheName
 * @param key
 * @param value
 */
public static void put(String cacheName, String key, Object value) {
  Cache cache = getCache(cacheName);
  if (null != cache) {
    Element element = new Element(key, value);
    cache.put(element);
  }
}

代码示例来源:origin: gocd/gocd

private static Ehcache createCacheIfRequired(String cacheName) {
  final CacheManager instance = CacheManager.newInstance(new Configuration().name(cacheName));
  synchronized (instance) {
    if (!instance.cacheExists(cacheName)) {
      instance.addCache(new net.sf.ehcache.Cache(cacheConfiguration(cacheName)));
    }
    return instance.getCache(cacheName);
  }
}

代码示例来源:origin: net.sf.ehcache/ehcache

Element element = get(key);
      map.put(key, element.getObjectValue());
  Future future = asynchronousLoadAll(missingKeys, loaderArgument);
  long cacheLoaderTimeoutMillis = configuration.getCacheLoaderTimeoutMillis();
  if (cacheLoaderTimeoutMillis > 0) {
    try {
    Element element = get(key);
    if (element != null) {
      map.put(key, element.getObjectValue());
    } else {
      map.put(key, null);
  throw new CacheException(e.getMessage() + " for key " + key, e);
} catch (ExecutionException e) {
  throw new CacheException(e.getMessage() + " for key " + key, e);
  Element element = get(key);
  if (element != null) {
    map.put(key, element.getObjectValue());
  } else {
    map.put(key, null);

代码示例来源:origin: ninjaframework/ninja

public Object get(String key) {
  Element e = ehCache.get(key);
  return (e == null) ? null : e.getObjectValue();
}

代码示例来源:origin: BroadleafCommerce/BroadleafCommerce

private synchronized Cache getHeap() {
  if (heap == null) {
    if (CacheManager.getInstance().cacheExists("hydrated-cache")) {
      heap = CacheManager.getInstance().getCache("hydrated-cache");
    } else {
      CacheConfiguration config = new CacheConfiguration("hydrated-cache", 0).eternal(true).overflowToDisk(false).maxElementsInMemory(100000);
      Cache cache = new Cache(config);
      CacheManager.create().addCache(cache);
      heap = cache;
    }
  }
  return heap;
}

代码示例来源:origin: BroadleafCommerce/BroadleafCommerce

private synchronized Cache getHeap() {
  if (offHeap == null) {
    if (CacheManager.getInstance().cacheExists("hydrated-offheap-cache")) {
      offHeap = CacheManager.getInstance().getCache("hydrated-offheap-cache");
    } else {
      CacheConfiguration config = new CacheConfiguration("hydrated-offheap-cache", 500).eternal(true).overflowToOffHeap(true).maxMemoryOffHeap("1400M");
      Cache cache = new Cache(config);
      CacheManager.create().addCache(cache);
      offHeap = cache;
    }
  }
  return offHeap;
}

代码示例来源:origin: net.sf.ehcache/ehcache

private void initSupportCache() {
  this.supportConfig = new CacheConfiguration();
  supportConfig.name(underlyingCache.getName() + "_" + getClass().getName() + "_refreshAheadSupport");
  supportConfig = supportConfig.persistence(new PersistenceConfiguration().strategy(Strategy.NONE));
  int activeSize = 2 * refreshAheadConfig.getBatchSize() * refreshAheadConfig.getNumberOfThreads();
  supportConfig = supportConfig.maxEntriesLocalHeap(activeSize);
  if (underlyingCache.getCacheConfiguration().isTerracottaClustered()) {
    supportConfig = supportConfig.persistence(new PersistenceConfiguration().strategy(Strategy.DISTRIBUTED));
  this.supportCache = new Cache(supportConfig);
  Ehcache prior = underlyingCache.getCacheManager().addCacheIfAbsent(supportCache);
  if (prior != supportCache) {
    throw new IllegalStateException("Unable to add refresh ahead support cache due to name collision: "

相关文章

微信公众号

最新文章

更多

Cache类方法