@Test public void testConfigFileHonorsClusteringOff() { final CacheManager cacheManager = new CacheManager( CacheManager.class.getResourceAsStream("/terracotta/ehcache-event-replication.xml")); try { final Cache cache = cacheManager.getCache("replication"); assertThat(cache, notNullValue()); final TerracottaConfiguration terracottaConfiguration = cache.getCacheConfiguration().getTerracottaConfiguration(); assertThat(terracottaConfiguration, notNullValue()); assertThat(terracottaConfiguration.isClustered(), is(false)); final List eventListenerConfigurations = cache.getCacheConfiguration().getCacheEventListenerConfigurations(); assertThat(eventListenerConfigurations, notNullValue()); assertThat(eventListenerConfigurations.size(), is(1)); assertThat( ((CacheConfiguration.CacheEventListenerFactoryConfiguration) eventListenerConfigurations.get(0)) .getFullyQualifiedClassPath(), equalTo(TerracottaCacheEventReplicationFactory.class.getName())); cache.put(new Element("key", "value")); assertThat((String) cache.get("key").getValue(), equalTo("value")); } finally { cacheManager.shutdown(); } }
@Around("findAllComPendendias()") public Object findAllTurmasComPendenciasMethodInterceptor(ProceedingJoinPoint joinPoint) throws Throwable { Object result = null; CacheManager cacheManager = CacheManager.create(new ClassPathResource("echache.xml").getInputStream()); Cache cache = cacheManager.getCache("turmas-pendencias-cache"); Object[] args = joinPoint.getArgs(); if (args[0] == null || args[1] == null) { result = joinPoint.proceed(); return result; } SimpleDateFormat df = new SimpleDateFormat("yyyy"); String exercicio = df.format((Date) args[0]); String organizacao = ((Long) args[1]).toString(); String key = exercicio + "-" + organizacao; Element element = cache.get(key); if (element == null) { result = joinPoint.proceed(); cache.put(new Element(key, result)); } else { Logger.getLogger(this.getClass().getName()) .log(Level.INFO, "Dados presentes no cache, não foi necessário acesso ao banco de dados"); result = element.getValue(); } return result; }
/** @see com.dianping.cache.core.CacheClient#clear() */ @Override public void clear() { defaultBlockingCache.removeAll(); for (String cacheName : manager.getCacheNames()) { manager.getCache(cacheName).removeAll(); } }
/** Drive everything to point of breakage within a 64MB VM. */ public void xTestHugePutsBreaksAsynchronous() throws CacheException, InterruptedException { // Give everything a chance to startup StopWatch stopWatch = new StopWatch(); Integer index = null; for (int i = 0; i < 500; i++) { for (int j = 0; j < 1000; j++) { index = Integer.valueOf(((1000 * i) + j)); cache1.put( new Element( index, "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA")); } } long elapsed = stopWatch.getElapsedTime(); long putTime = ((elapsed / 1000)); LOG.info("Put Elapsed time: " + putTime); // assertTrue(putTime < 8); assertEquals(100000, cache1.getSize()); Thread.sleep(100000); assertEquals(20000, manager2.getCache("sampleCache1").getSize()); assertEquals(20000, manager3.getCache("sampleCache1").getSize()); assertEquals(20000, manager4.getCache("sampleCache1").getSize()); assertEquals(20000, manager5.getCache("sampleCache1").getSize()); }
/** * {@inheritDoc} Sets up two caches: cache1 is local. cache2 is to be receive updates * * @throws Exception */ @Override @Before public void setUp() throws Exception { // Required to get SoftReference tests to pass. The VM clean up SoftReferences rather than // allocating // memory to -Xmx! // forceVMGrowth(); // System.gc(); MulticastKeepaliveHeartbeatSender.setHeartBeatInterval(1000); manager1 = new CacheManager(AbstractCachePerfTest.TEST_CONFIG_DIR + "ehcache-distributed1.xml"); manager2 = new CacheManager(AbstractCachePerfTest.TEST_CONFIG_DIR + "ehcache-distributed2.xml"); manager3 = new CacheManager(AbstractCachePerfTest.TEST_CONFIG_DIR + "ehcache-distributed3.xml"); manager4 = new CacheManager(AbstractCachePerfTest.TEST_CONFIG_DIR + "ehcache-distributed4.xml"); manager5 = new CacheManager(AbstractCachePerfTest.TEST_CONFIG_DIR + "ehcache-distributed5.xml"); // manager6 = new CacheManager(AbstractCacheTest.TEST_CONFIG_DIR + // "distribution/ehcache-distributed-jndi6.xml"); // allow cluster to be established Thread.sleep(1020); cache1 = manager1.getCache(cacheName); cache1.removeAll(); cache2 = manager2.getCache(cacheName); cache2.removeAll(); // enable distributed removeAlls to finish Thread.sleep(1500); }
@PostConstruct public void initialize() { stats = new Stats(); boolean cacheExists = cacheManager.cacheExists(getName()); if (cacheExists) { if (failOnDuplicateCache) { throw new RuntimeException("A previous cache with name [" + getName() + "] exists."); } else { log.warn("skip duplicate cache " + getName()); ehcache = cacheManager.getCache(getName()); } } if (!cacheExists) { ehcache = new Cache( getName(), getMaxElementsInMemory(), getMemoryStoreEvictionPolicy(), isOverflowToDisk(), getDiskStorePath(), isEternal(), getTimeToLiveSeconds(), getTimeToIdleSeconds(), isDiskPersistent(), getDiskExpiryThreadIntervalSeconds(), null); cacheManager.addCache(ehcache); ehcache.setStatisticsEnabled(statisticsEnabled); } }
/** ** Private Methods ** */ private CacheEntry getCache(ProceedingJoinPoint pjp) { String name = getCacheName(pjp); CacheEntry entry = _entries.get(name); if (entry == null) { Method method = _cacheableMethodKeyFactoryManager.getMatchingMethodForJoinPoint(pjp); CacheableMethodKeyFactory keyFactory = getKeyFactory(pjp, method); boolean valueSerializable = isValueSerializable(pjp, method); Cache cache = _cacheManager.getCache(name); if (cache == null) { cache = createCache(pjp, name); if (cache == null) { _cacheManager.addCache(name); cache = _cacheManager.getCache(name); } else { _cacheManager.addCache(cache); } } entry = new CacheEntry(keyFactory, valueSerializable, cache); _entries.put(name, entry); } return entry; }
@Bean public CacheManager cacheManager() { log.debug("Starting Ehcache"); cacheManager = net.sf.ehcache.CacheManager.create(); cacheManager .getConfiguration() .setMaxBytesLocalHeap( env.getProperty("cache.ehcache.maxBytesLocalHeap", String.class, "16M")); log.debug("Registering Ehcache Metrics gauges"); Set<EntityType<?>> entities = entityManager.getMetamodel().getEntities(); for (EntityType<?> entity : entities) { String name = entity.getName(); if (name == null || entity.getJavaType() != null) { name = entity.getJavaType().getName(); } Assert.notNull(name, "entity cannot exist without a identifier"); net.sf.ehcache.Cache cache = cacheManager.getCache(name); if (cache != null) { cache .getCacheConfiguration() .setTimeToLiveSeconds(env.getProperty("cache.timeToLiveSeconds", Long.class, 3600L)); net.sf.ehcache.Ehcache decoratedCache = InstrumentedEhcache.instrument(metricRegistry, cache); cacheManager.replaceCacheWithDecoratedCache(cache, decoratedCache); } } EhCacheCacheManager ehCacheManager = new EhCacheCacheManager(); ehCacheManager.setCacheManager(cacheManager); return ehCacheManager; }
protected static CacheManager getCacheManagerMaxbytes() { Configuration configuration = new Configuration(); configuration.setName("testCacheManagerProgrammatic"); configuration.setMaxBytesLocalDisk("10M"); configuration.setMaxBytesLocalHeap("5M"); TerracottaClientConfiguration terracottaConfiguration = new TerracottaClientConfiguration().url(CLUSTER_URL); configuration.addTerracottaConfig(terracottaConfiguration); CacheConfiguration myCache = new CacheConfiguration() .eternal(false) .name("testCache2") .terracotta(new TerracottaConfiguration()); configuration.addCache(myCache); ManagementRESTServiceConfiguration managementRESTServiceConfiguration = new ManagementRESTServiceConfiguration(); managementRESTServiceConfiguration.setBind("0.0.0.0:" + STANDALONE_REST_AGENT_PORT); managementRESTServiceConfiguration.setEnabled(true); configuration.addManagementRESTService(managementRESTServiceConfiguration); CacheManager mgr = new CacheManager(configuration); Cache exampleCache = mgr.getCache("testCache2"); assert (exampleCache != null); return mgr; }
@Test public void testBasicReplication() throws Exception { LOG.info("START TEST"); final Ehcache cache1 = manager1.getEhcache(cacheName); final Ehcache cache2 = manager2.getEhcache(cacheName); final Ehcache cache3 = manager3.getEhcache(cacheName); final Ehcache cache4 = manager4.getEhcache(cacheName); for (int i = 0; i < NBR_ELEMENTS; i++) { cache1.put(new Element(i, "testdat")); } // Wait up to 3 seconds for the caches to become coherent CacheTestUtilities.waitForReplication(NBR_ELEMENTS, MAX_WAIT_TIME, cache2, cache3, cache4); assertEquals(NBR_ELEMENTS, cache1.getKeys().size()); assertEquals(NBR_ELEMENTS, cache2.getKeys().size()); assertEquals(NBR_ELEMENTS, cache3.getKeys().size()); assertEquals(NBR_ELEMENTS, cache4.getKeys().size()); cache1.removeAll(); // Wait up to 3 seconds for the caches to become coherent CacheTestUtilities.waitForReplication(0, MAX_WAIT_TIME, cache2, cache3, cache4); assertEquals(0, cache1.getKeys().size()); assertEquals(0, cache2.getKeys().size()); assertEquals(0, cache3.getKeys().size()); assertEquals(0, cache4.getKeys().size()); LOG.info("END TEST"); }
@Bean public net.sf.ehcache.CacheManager customEhCacheCacheManager() { net.sf.ehcache.CacheManager cacheManager = mock(net.sf.ehcache.CacheManager.class); given(cacheManager.getStatus()).willReturn(Status.STATUS_ALIVE); given(cacheManager.getCacheNames()).willReturn(new String[0]); return cacheManager; }
public void testSimultaneousPutRemove() throws InterruptedException { cacheName = SAMPLE_CACHE2; // Synced one Ehcache cache1 = manager1.getEhcache(cacheName); Ehcache cache2 = manager2.getEhcache(cacheName); Serializable key = "1"; Serializable value = new Date(); Element element = new Element(key, value); // Put cache1.put(element); Thread.currentThread().sleep(1000); cache2.remove(element.getKey()); Thread.currentThread().sleep(1000); assertNull(cache1.get(element.getKey())); manager1.clearAll(); Thread.currentThread().sleep(1000); cache2.put(element); cache2.remove(element.getKey()); Thread.currentThread().sleep(1000); cache1.put(element); Thread.currentThread().sleep(1000); assertNotNull(cache2.get(element.getKey())); manager1.clearAll(); Thread.currentThread().sleep(1000); }
protected static CacheManager getCacheManagerMaxEntries() { Configuration configuration = new Configuration(); configuration.setName("testCacheManager"); configuration.addTerracottaConfig(new TerracottaClientConfiguration().url(CLUSTER_URL)); CacheConfiguration defaultCacheConfiguration = new CacheConfiguration() .eternal(true) .terracotta(new TerracottaConfiguration()) .maxEntriesLocalHeap(10000); CacheConfiguration cacheConfiguration = new CacheConfiguration() .name("testCache") .terracotta(new TerracottaConfiguration()) .maxEntriesLocalHeap(10000); configuration.setDefaultCacheConfiguration(defaultCacheConfiguration); configuration.addCache(cacheConfiguration); ManagementRESTServiceConfiguration managementRESTServiceConfiguration = new ManagementRESTServiceConfiguration(); managementRESTServiceConfiguration.setBind("0.0.0.0:" + STANDALONE_REST_AGENT_PORT); managementRESTServiceConfiguration.setEnabled(true); configuration.addManagementRESTService(managementRESTServiceConfiguration); CacheManager mgr = new CacheManager(configuration); Cache exampleCache = mgr.getCache("testCache"); assert (exampleCache != null); return mgr; }
@Around("findTurmaEfetiva()") public Object findTurmaEfetivaMethodInterceptor(ProceedingJoinPoint joinPoint) throws Throwable { Object result = null; CacheManager cacheManager = CacheManager.create(new ClassPathResource("echache.xml").getInputStream()); Cache cache = cacheManager.getCache("turmas-efetivas-cache"); Object[] args = joinPoint.getArgs(); Long turmaId = (Long) args[0]; Element element = cache.get(turmaId); if (element == null) { result = joinPoint.proceed(); cache.put(new Element(turmaId, result)); } else { Logger.getLogger(this.getClass().getName()) .log( Level.INFO, "Dados presentes no cache de turmas, não foi necessário acesso ao banco de dados"); result = element.getValue(); } return result; }
@Override public EhCache buildCache(CacheSetting setting) throws CacheException { String name = StringUtil.joinString(setting.getRegion(), setting.getConfigKey()); EhCache ehcache = cacheManager.get(name); if (ehcache == null) { try { synchronized (cacheManager) { ehcache = cacheManager.get(name); if (ehcache == null) { // log.debug("Could not find configuration [" + name // + "]; using defaults."); Ehcache ehcache2 = manager.addCacheIfAbsent(name); if (ehcache2 != null) { if (setting.getCacheExpire() == CacheExpire.SlidingTime) { ehcache2.getCacheConfiguration().setTimeToIdleSeconds(setting.getExpireTime()); ehcache2.getCacheConfiguration().setTimeToLiveSeconds(0); } else if (setting.getCacheExpire() == CacheExpire.AbsoluteTime) { ehcache2.getCacheConfiguration().setTimeToLiveSeconds(setting.getExpireTime()); ehcache2.getCacheConfiguration().setTimeToIdleSeconds(0); } } Cache cache = manager.getCache(name); // log.debug("started EHCache region: " + name); LoggerFactory.getLogger(this.getClass()).info("init ehcache " + cache); ehcache = new EhCache(cache, setting); cacheManager.put(name, ehcache); } } } catch (Exception e) { throw new CacheException(e); } } return ehcache; }
@Test public void testParallelShutdown() throws Exception { final CacheManager manager = new CacheManager( new Configuration() .name("testEqualsDriver") .cache( new CacheConfiguration() .name("parallel") .maxBytesLocalHeap(64, MemoryUnit.MEGABYTES))); Cache parallel = manager.getCache("parallel"); CacheDriver loadParallel = CacheLoader.load(ehcache(parallel)) .using(StringGenerator.integers(), ByteArrayGenerator.fixedSize(128)) .sequentially() .untilFilled(); final CacheDriver driver = ParallelDriver.inParallel(4, loadParallel); await() .atMost(20, TimeUnit.SECONDS) .until( new Callable<Boolean>() { @Override public Boolean call() throws Exception { driver.run(); return true; } }); manager.shutdown(); }
/** Basically does the same as CacheManager.getCache() except that this method is lock free. */ private static CacheManager getCacheManager(String cacheManagerName) { for (CacheManager cacheManager : CacheManager.ALL_CACHE_MANAGERS) { if (cacheManager.getName().equals(cacheManagerName)) { return cacheManager; } } return null; }
private void updateSchoolCache(SchoolAccount accnt) { cacheManager .getCache(CacheVariables.CACHE_SCHOOL_ACCOUNTS_BY_USERNAME) .put(new Element(accnt.getUsername(), accnt)); cacheManager .getCache(CacheVariables.CACHE_ACCOUNTS_BY_UUID) .put(new Element(accnt.getUuid(), accnt)); }
/** Does a down cache manager in the cluster get removed? */ @Test public void testRemoteCachePeersDetectsDownCacheManager() throws InterruptedException { // Drop a CacheManager from the cluster manager3.shutdown(); // Allow change detection to occur. Heartbeat 1 second and is not stale until 5000 waitForClusterMembership( 11020, TimeUnit.MILLISECONDS, Arrays.asList(manager1.getCacheNames()), manager1, manager2); }
static { if (eternalCache == null) { eternalCache = CacheManager.getInstance().getCache("eternalCache"); } if (dictCache == null) { dictCache = CacheManager.getInstance().getCache("dictCache"); } }
public static synchronized Cache getInstance() { if (ehCache == null) { logger.info("The first time to create cache!"); CacheManager manager = CacheManager.create(); ehCache = manager.getCache("ehcache"); } return ehCache; }
private void clearChache() throws IOException { CacheManager cacheManager = CacheManager.create(new ClassPathResource("echache.xml").getInputStream()); Cache cache1 = cacheManager.getCache("turmas-efetivas-cache"); Cache cache2 = cacheManager.getCache("turmas-pendencias-cache"); cache1.removeAll(); cache2.removeAll(); }
/** * 获得一个Cache,没有则创建一个。 * * @param cacheName * @return */ private static Cache getCache(String cacheName) { Cache cache = cacheManager.getCache(cacheName); if (cache == null) { cacheManager.addCache(cacheName); cache = cacheManager.getCache(cacheName); cache.getCacheConfiguration().setEternal(true); } return cache; }
private static Cache[] allCaches(CacheManager cacheManager) { int i = 0; Cache[] caches = new Cache[cacheManager.getCacheNames().length]; for (String name : cacheManager.getCacheNames()) { caches[i++] = cacheManager.getCache(name); } return caches; }
public Cache getEhCache() { Cache cache = ehcacheManager.getCache(name); if (null == cache) { ehcacheManager.addCache(name); return ehcacheManager.getCache(name); } else { return cache; } }
public void testConfig() throws InterruptedException { cacheName = SAMPLE_CACHE_NOREP; Ehcache cache1 = manager1.getEhcache(cacheName); Ehcache cache2 = manager2.getEhcache(cacheName); Element element = new Element(new Integer(1), new Date()); cache2.put(element); Thread.currentThread().sleep(1000); assertTrue(cache1.getKeys().size() == 0 && cache2.getKeys().size() == 1); }
private void reconfigureCache(String name, JHipsterProperties jHipsterProperties) { net.sf.ehcache.Cache cache = cacheManager.getCache(name); if (cache != null) { cache .getCacheConfiguration() .setTimeToLiveSeconds(jHipsterProperties.getCache().getTimeToLiveSeconds()); net.sf.ehcache.Ehcache decoratedCache = InstrumentedEhcache.instrument(metricRegistry, cache); cacheManager.replaceCacheWithDecoratedCache(cache, decoratedCache); } }
/** * 清除缓存 * * @param cacheName * @return */ public boolean clearCache(String cacheName) { CacheManager cacheManagerObject = cacheManager.getObject(); Cache cache = cacheManagerObject.getCache(cacheName); if (cache != null) { cache.removeAll(); return Boolean.TRUE; } else { return Boolean.FALSE; } }
/** Does the RMI listener stop? */ @Test public void testListenerShutsdown() { CacheManagerPeerListener cachePeerListener = manager1.getCachePeerListener("RMI"); List cachePeers1 = cachePeerListener.getBoundCachePeers(); assertEquals(1, cachePeers1.size()); assertEquals(Status.STATUS_ALIVE, cachePeerListener.getStatus()); manager1.shutdown(); assertEquals(Status.STATUS_SHUTDOWN, cachePeerListener.getStatus()); }
public void tearDown() throws Exception { LOG.debug("Tearing down cm1"); manager1.shutdown(); LOG.debug("Tearing down cm2"); manager2.shutdown(); LOG.debug("Tearing down cm3"); manager3.shutdown(); LOG.debug("Tearing down cm4"); manager4.shutdown(); }