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

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

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

Ehcache介绍

[英]An interface for Ehcache.

Ehcache is the central interface. 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 an EhCache can be obtained through the CacheManager. An Ehcache 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.

Statistics on cache usage are collected and made available through public methods.
[中]Ehcache的接口。
Ehcache是中央接口。缓存有元素,由CacheManager管理。缓存执行逻辑操作。它将物理实现委托给它的网络。旧金山。ehcache。百货商店商店。
可以通过CacheManager获得对EhCache的引用。由此获得的Ehcache保证具有status status#status_ALIVE。对于引发IllegalStateException的任何方法,都会检查此状态,如果该方法不处于活动状态,则会引发相同的异常。如果在调用CacheManager#shutdown后调用,通常会发生这种情况。
缓存使用情况的统计信息是通过公共方法收集和提供的。

代码示例

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

public <T> T get(String key, Supplier<T> compute) {
  Element element = ehcache.get(key);
  if (element != null) {
    return (T) element.getObjectValue();
  }
  synchronized (key.intern()) {
    element = ehcache.get(key);
    if (element != null) {
      return (T) element.getObjectValue();
    }
    T object = compute.get();
    ehcache.put(new Element(key, object));
    return object;
  }
}

代码示例来源:origin: spring-projects/spring-framework

@Override
public void evict(Object key) {
  this.cache.remove(key);
}

代码示例来源:origin: spring-projects/spring-security

protected Ehcache getCache() {
  Ehcache cache = cacheManager.getCache("basiclookuptestcache");
  cache.removeAll();
  return cache;
}

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

/**
 * Removes all elements in the cache, but leaves the cache in a useable state.
 */
public void clear() throws CacheException {
  if (log.isTraceEnabled()) {
    log.trace("Clearing all objects from cache [" + cache.getName() + "]");
  }
  try {
    cache.removeAll();
  } catch (Throwable t) {
    throw new CacheException(t);
  }
}

代码示例来源:origin: spring-projects/spring-framework

logger.debug("Using default EhCache CacheManager for cache region '" + cacheName + "'");
this.cacheManager = CacheManager.getInstance();
boolean cacheExists = this.cacheManager.cacheExists(cacheName);
    logger.debug("Using existing EhCache cache region '" + cacheName + "'");
  rawCache = this.cacheManager.getEhcache(cacheName);
  rawCache.setBootstrapCacheLoader(this.bootstrapCacheLoader);
    rawCache.getCacheEventNotificationService().registerListener(listener);
  rawCache.setDisabled(true);

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

/**
 * {@inheritDoc}
 */
public boolean putFromLoad(Object key, Object value, long txTimestamp,
              Object version, boolean minimalPutOverride) throws CacheException {
  try {
    if (minimalPutOverride && ehcache.get(key) != null) {
      return false;
    }
    //OptimisticCache? versioning?
    ehcache.put(new Element(key, value));
    return true;
  } catch (net.sf.ehcache.CacheException e) {
    throw new CacheException(e);
  }
}

代码示例来源:origin: hibernate/hibernate-orm

@Override
public void putIntoCache(Object key, Object value, SharedSessionContractImplementor session) {
  try {
    final Element element = new Element( key, value );
    getCache().put( element );
  }
  catch (IllegalArgumentException | IllegalStateException e) {
    throw new CacheException( e );
  }
  catch (net.sf.ehcache.CacheException e) {
    if ( e instanceof NonStopCacheException ) {
      HibernateNonstopCacheExceptionHandler.getInstance()
          .handleNonstopCacheException( (NonStopCacheException) e );
    }
    else {
      throw new CacheException( e );
    }
  }
}

代码示例来源: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: "
  prior.removeAll();
  underlyingCache.registerCacheExtension(new CacheExtension() {

代码示例来源:origin: spring-projects/spring-security

@Test
public void evictCacheSerializable() throws Exception {
  when(cache.get(acl.getObjectIdentity()))
      .thenReturn(new Element(acl.getId(), acl));
  myCache.evictFromCache(acl.getObjectIdentity());
  verify(cache).remove(acl.getId());
  verify(cache).remove(acl.getObjectIdentity());
}

代码示例来源:origin: hibernate/hibernate-orm

@Override
public Object getFromCache(Object key, SharedSessionContractImplementor session) {
  try {
    final Element element = getCache().get( key );
    if ( element == null ) {
      return null;
    }
    else {
      return element.getObjectValue();
    }
  }
  catch (net.sf.ehcache.CacheException e) {
    if ( e instanceof NonStopCacheException ) {
      HibernateNonstopCacheExceptionHandler.getInstance()
          .handleNonstopCacheException( (NonStopCacheException) e );
      return null;
    }
    else {
      throw new CacheException( e );
    }
  }
}

代码示例来源:origin: spring-projects/spring-security

public void putUserInCache(UserDetails user) {
  Element element = new Element(user.getUsername(), user);
  if (logger.isDebugEnabled()) {
    logger.debug("Cache put: " + element.getKey());
  }
  cache.put(element);
}

代码示例来源:origin: spring-projects/spring-framework

@Test
public void testEhCacheFactoryBeanWithSelfPopulatingCache() {
  EhCacheManagerFactoryBean cacheManagerFb = new EhCacheManagerFactoryBean();
  cacheManagerFb.afterPropertiesSet();
  try {
    CacheManager cm = cacheManagerFb.getObject();
    EhCacheFactoryBean cacheFb = new EhCacheFactoryBean();
    cacheFb.setCacheManager(cm);
    cacheFb.setCacheName("myCache1");
    cacheFb.setCacheEntryFactory(key -> key);
    assertEquals(cacheFb.getObjectType(), SelfPopulatingCache.class);
    cacheFb.afterPropertiesSet();
    Ehcache myCache1 = cm.getEhcache("myCache1");
    assertTrue(myCache1 instanceof SelfPopulatingCache);
    assertEquals("myKey1", myCache1.get("myKey1").getObjectValue());
  }
  finally {
    cacheManagerFb.destroy();
  }
}

代码示例来源:origin: spring-projects/spring-framework

@Override
public void put(Object key, @Nullable Object value) {
  this.cache.put(new Element(key, value));
}

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

/**
 * Loads an existing EhCache from the cache manager, or starts a new cache if one is not found.
 *
 * @param name the name of the cache to load/create.
 */
public final <K, V> Cache<K, V> getCache(String name) throws CacheException {
  if (log.isTraceEnabled()) {
    log.trace("Acquiring EhCache instance named [" + name + "]");
  }
  try {
    net.sf.ehcache.Ehcache cache = ensureCacheManager().getEhcache(name);
    if (cache == null) {
      if (log.isInfoEnabled()) {
        log.info("Cache with name '{}' does not yet exist.  Creating now.", name);
      }
      this.manager.addCache(name);
      cache = manager.getCache(name);
      if (log.isInfoEnabled()) {
        log.info("Added EhCache named [" + name + "]");
      }
    } else {
      if (log.isInfoEnabled()) {
        log.info("Using existing EHCache named [" + cache.getName() + "]");
      }
    }
    return new EhCache<K, V>(cache);
  } catch (net.sf.ehcache.CacheException e) {
    throw new CacheException(e);
  }
}

代码示例来源:origin: org.sakaiproject.kernel/sakai-kernel-impl

buf.append("\n\n");
String[] allCacheNames = cacheManager.getCacheNames();
Arrays.sort(allCacheNames);
ArrayList<Ehcache> caches = new ArrayList<Ehcache>(allCacheNames.length);
for (String cacheName : allCacheNames) {
  Ehcache cache = cacheManager.getCache(cacheName);
  caches.add(cache);
  buf.append(cache.toString());
  buf.append("\n");
  long maxEntries = cache.getCacheConfiguration().getMaxEntriesLocalHeap();
  long ttlSecs = cache.getCacheConfiguration().getTimeToLiveSeconds();
  long ttiSecs = cache.getCacheConfiguration().getTimeToIdleSeconds();
  boolean eternal = cache.getCacheConfiguration().isEternal();
  if (maxEntries == maxEntriesDefault && ttlSecs == ttlSecsDefault && ttiSecs == ttiSecsDefault && eternal == eternalDefault) {
    buf.append("# memory.").append(cache.getName()).append(" *ALL DEFAULTS*\n");
  } else {
    buf.append("memory.").append(cache.getName()).append("=");
    boolean first = true;
    if (maxEntries != maxEntriesDefault) {
    if (cache.getCacheConfiguration().isOverflowToDisk()) {
      buf.append("# NOTE: ").append(cache.getName()).append(" is configured for Overflow(disk), ").append(cache.getCacheConfiguration().getMaxEntriesLocalDisk()).append(" entries\n");

代码示例来源:origin: spring-projects/spring-framework

@Test
public void testExpiredElements() throws Exception {
  Assume.group(TestGroup.LONG_RUNNING);
  String key = "brancusi";
  String value = "constantin";
  Element brancusi = new Element(key, value);
  // ttl = 10s
  brancusi.setTimeToLive(3);
  nativeCache.put(brancusi);
  assertEquals(value, cache.get(key).get());
  // wait for the entry to expire
  Thread.sleep(5 * 1000);
  assertNull(cache.get(key));
}

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

private void doLoad(final Ehcache cache) {
  CacheManager manager = cache.getCacheManager();
  if (manager == null) {
    throw new CacheException("Cache must belong to a cache manager to bootstrap");
  }
  DiskStorePathManager pathManager = diskStorePathManager != null ? diskStorePathManager : cache.getCacheManager()
      .getDiskStorePathManager();
  final RotatingSnapshotFile snapshotFile = new RotatingSnapshotFile(pathManager, cache.getName(), manager.getConfiguration().getClassLoader());
  try {
    final Set<Object> keys = snapshotFile.readAll();
    int loaded = 0;
    for (Object key : keys) {
      if (isInMemoryLimitReached(cache, loaded)) {
        break;
      }
      cache.get(key);
      loaded++;
    }
    LOG.info("Finished loading {} keys (of {} on disk) from previous snapshot for Cache '{}'",
        new Object[] {Integer.valueOf(loaded), keys.size(), cache.getName()});
  } catch (IOException e) {
    LOG.error("Couldn't load keySet for Cache '{}'", cache.getName(), e);
  }
  if (doKeySnapshot) {
    keySnapshotter = new KeySnapshotter(cache, interval, doKeySnapshotOnDedicatedThread, snapshotFile);
  }
}

代码示例来源:origin: spring-projects/spring-framework

@Override
@SuppressWarnings("unchecked")
@Nullable
public <T> T get(Object key, @Nullable Class<T> type) {
  Element element = this.cache.get(key);
  Object value = (element != null ? element.getObjectValue() : null);
  if (value != null && type != null && !type.isInstance(value)) {
    throw new IllegalStateException(
        "Cached value is not of required type [" + type.getName() + "]: " + value);
  }
  return (T) value;
}

代码示例来源:origin: spring-projects/spring-security

@Test
public void getFromCacheObjectIdentity() throws Exception {
  when(cache.get(acl.getId())).thenReturn(new Element(acl.getId(), acl));
  assertThat(myCache.getFromCache(acl.getId())).isEqualTo(acl);
}

代码示例来源:origin: spring-projects/spring-security

@Test
public void putInCache() throws Exception {
  myCache.putInCache(acl);
  verify(cache, times(2)).put(element.capture());
  assertThat(element.getValue().getKey()).isEqualTo(acl.getId());
  assertThat(element.getValue().getObjectValue()).isEqualTo(acl);
  assertThat(element.getAllValues().get(0).getKey()).isEqualTo(
      acl.getObjectIdentity());
  assertThat(element.getAllValues().get(0).getObjectValue()).isEqualTo(acl);
}

相关文章

Ehcache类方法