Java Code Examples for net.sf.ehcache.CacheManager#getCache()

The following examples show how to use net.sf.ehcache.CacheManager#getCache() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: EHCacheProvider.java    From pentaho-reporting with GNU Lesser General Public License v2.1 7 votes vote down vote up
public ResourceDataCache createDataCache() {
  try {
    final CacheManager manager = getCacheManager();
    synchronized( manager ) {
      if ( manager.cacheExists( DATA_CACHE_NAME ) == false ) {
        final Cache libloaderCache = new Cache( DATA_CACHE_NAME,   // cache name
          500,         // maxElementsInMemory
          false,       // overflowToDisk
          false,       // eternal
          600,         // timeToLiveSeconds
          600,         // timeToIdleSeconds
          false,       // diskPersistent
          120 );        // diskExpiryThreadIntervalSeconds
        manager.addCache( libloaderCache );
        return new EHResourceDataCache( libloaderCache );
      } else {
        return new EHResourceDataCache( manager.getCache( DATA_CACHE_NAME ) );
      }
    }
  } catch ( CacheException e ) {
    logger.debug( "Failed to create EHCache libloader-data cache", e );
    return null;
  }
}
 
Example 2
Source File: EhCacheSupportTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void testAcceptExistingCacheManager() throws Exception {
	EhCacheManagerFactoryBean cacheManagerFb = new EhCacheManagerFactoryBean();
	cacheManagerFb.setCacheManagerName("myCacheManager");
	assertEquals(CacheManager.class, cacheManagerFb.getObjectType());
	assertTrue("Singleton property", cacheManagerFb.isSingleton());
	cacheManagerFb.afterPropertiesSet();
	try {
		CacheManager cm = cacheManagerFb.getObject();
		assertTrue("Loaded CacheManager with no caches", cm.getCacheNames().length == 0);
		Cache myCache1 = cm.getCache("myCache1");
		assertTrue("No myCache1 defined", myCache1 == null);

		EhCacheManagerFactoryBean cacheManagerFb2 = new EhCacheManagerFactoryBean();
		cacheManagerFb2.setCacheManagerName("myCacheManager");
		cacheManagerFb2.setAcceptExisting(true);
		cacheManagerFb2.afterPropertiesSet();
		CacheManager cm2 = cacheManagerFb2.getObject();
		assertSame(cm, cm2);
		cacheManagerFb2.destroy();
	}
	finally {
		cacheManagerFb.destroy();
	}
}
 
Example 3
Source File: EhCacheSupportTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testAcceptExistingCacheManager() {
	EhCacheManagerFactoryBean cacheManagerFb = new EhCacheManagerFactoryBean();
	cacheManagerFb.setCacheManagerName("myCacheManager");
	assertEquals(CacheManager.class, cacheManagerFb.getObjectType());
	assertTrue("Singleton property", cacheManagerFb.isSingleton());
	cacheManagerFb.afterPropertiesSet();
	try {
		CacheManager cm = cacheManagerFb.getObject();
		assertTrue("Loaded CacheManager with no caches", cm.getCacheNames().length == 0);
		Cache myCache1 = cm.getCache("myCache1");
		assertTrue("No myCache1 defined", myCache1 == null);

		EhCacheManagerFactoryBean cacheManagerFb2 = new EhCacheManagerFactoryBean();
		cacheManagerFb2.setCacheManagerName("myCacheManager");
		cacheManagerFb2.setAcceptExisting(true);
		cacheManagerFb2.afterPropertiesSet();
		CacheManager cm2 = cacheManagerFb2.getObject();
		assertSame(cm, cm2);
		cacheManagerFb2.destroy();
	}
	finally {
		cacheManagerFb.destroy();
	}
}
 
Example 4
Source File: EhCacheSupportTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
public void testCacheManagerFromConfigFile() {
	EhCacheManagerFactoryBean cacheManagerFb = new EhCacheManagerFactoryBean();
	cacheManagerFb.setConfigLocation(new ClassPathResource("testEhcache.xml", getClass()));
	cacheManagerFb.setCacheManagerName("myCacheManager");
	cacheManagerFb.afterPropertiesSet();
	try {
		CacheManager cm = cacheManagerFb.getObject();
		assertTrue("Correct number of caches loaded", cm.getCacheNames().length == 1);
		Cache myCache1 = cm.getCache("myCache1");
		assertFalse("myCache1 is not eternal", myCache1.getCacheConfiguration().isEternal());
		assertTrue("myCache1.maxElements == 300", myCache1.getCacheConfiguration().getMaxEntriesLocalHeap() == 300);
	}
	finally {
		cacheManagerFb.destroy();
	}
}
 
Example 5
Source File: EhcacheApiTest.java    From spring-tutorial with Creative Commons Attribution Share Alike 4.0 International 6 votes vote down vote up
/**
 * 使用自定义配置添加缓存,注意缓存未添加进CacheManager之前并不可用
 */
@Test
public void addAndRemove02() {
	CacheManager singletonManager = CacheManager.create();

	// 添加缓存
	Cache memoryOnlyCache = new Cache("testCache2", 5000, false, false, 5, 2);
	singletonManager.addCache(memoryOnlyCache);

	// 打印配置信息和状态
	Cache test = singletonManager.getCache("testCache2");
	System.out.println("cache name:" + test.getCacheConfiguration().getName());
	System.out.println("cache status:" + test.getStatus().toString());
	System.out.println("maxElementsInMemory:" + test.getCacheConfiguration().getMaxElementsInMemory());
	System.out.println("timeToIdleSeconds:" + test.getCacheConfiguration().getTimeToIdleSeconds());
	System.out.println("timeToLiveSeconds:" + test.getCacheConfiguration().getTimeToLiveSeconds());

	// 删除缓存
	singletonManager.removeCache("testCache2");
	System.out.println("cache status:" + test.getStatus().toString());
}
 
Example 6
Source File: EhCacheSupportTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void testCacheManagerConflict() throws Exception {
	EhCacheManagerFactoryBean cacheManagerFb = new EhCacheManagerFactoryBean();
	cacheManagerFb.setCacheManagerName("myCacheManager");
	assertEquals(CacheManager.class, cacheManagerFb.getObjectType());
	assertTrue("Singleton property", cacheManagerFb.isSingleton());
	cacheManagerFb.afterPropertiesSet();
	try {
		CacheManager cm = cacheManagerFb.getObject();
		assertTrue("Loaded CacheManager with no caches", cm.getCacheNames().length == 0);
		Cache myCache1 = cm.getCache("myCache1");
		assertTrue("No myCache1 defined", myCache1 == null);

		EhCacheManagerFactoryBean cacheManagerFb2 = new EhCacheManagerFactoryBean();
		cacheManagerFb2.setCacheManagerName("myCacheManager");
		cacheManagerFb2.afterPropertiesSet();
		fail("Should have thrown CacheException because of naming conflict");
	}
	catch (CacheException ex) {
		// expected
	}
	finally {
		cacheManagerFb.destroy();
	}
}
 
Example 7
Source File: CacheInformationProvider.java    From gocd with Apache License 2.0 6 votes vote down vote up
@Override
public Map<String, Object> asJson() {
    LinkedHashMap<String, Object> json = new LinkedHashMap<>();

    for (CacheManager cacheManager : CacheManager.ALL_CACHE_MANAGERS) {
        LinkedHashMap<String, Object> jsonForManager = new LinkedHashMap<>();
        json.put(cacheManager.getName(), jsonForManager);

        for (String cacheName : cacheManager.getCacheNames()) {
            Cache cache = cacheManager.getCache(cacheName);
            LinkedHashMap<String, Object> cacheJson = new LinkedHashMap<>();
            jsonForManager.put(cacheName, cacheJson);

            cacheJson.put("Cache configuration information", getCacheConfigurationInformationAsJson(cache));
            cacheJson.put("Cache runtime information", getCacheRuntimeInformationAsJson(cache));
        }
    }

    return json;
}
 
Example 8
Source File: EhCacheSupportTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
public void testCacheManagerFromConfigFile() throws Exception {
	EhCacheManagerFactoryBean cacheManagerFb = new EhCacheManagerFactoryBean();
	cacheManagerFb.setConfigLocation(new ClassPathResource("testEhcache.xml", getClass()));
	cacheManagerFb.setCacheManagerName("myCacheManager");
	cacheManagerFb.afterPropertiesSet();
	try {
		CacheManager cm = cacheManagerFb.getObject();
		assertTrue("Correct number of caches loaded", cm.getCacheNames().length == 1);
		Cache myCache1 = cm.getCache("myCache1");
		assertFalse("myCache1 is not eternal", myCache1.getCacheConfiguration().isEternal());
		assertTrue("myCache1.maxElements == 300", myCache1.getCacheConfiguration().getMaxElementsInMemory() == 300);
	}
	finally {
		cacheManagerFb.destroy();
	}
}
 
Example 9
Source File: EhCacheManagerFactoryBean.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
@Override
public void afterPropertiesSet() {
       super.afterPropertiesSet();
	//Now look for any custom configuration.
   	CacheManager cm = (CacheManager) this.getObject();
   	if (cm != null) {
   		String cacheNames[]= cm.getCacheNames();

   		//Check for old configuration properties.
   		for (String cacheName:cacheNames) {
   			if(serverConfigurationService.getString(cacheName) == null) {
   				log.warn("Old cache configuration "+ cacheName+ " must be changed to memory."+ cacheName);
   			}
   			String config = serverConfigurationService.getString("memory."+ cacheName);
   			if (config != null && config.length() > 0) {
   				log.info("Found configuration override for cache: "+ cacheName+ " of: "+ config);
   				Cache cache = cm.getCache(cacheName);
   				if (cache != null) {
   					new CacheInitializer().configure(config).initialize(cache.getCacheConfiguration());
   				}
   			}
   		}
   	}
   }
 
Example 10
Source File: EhCacheManagerFactoryBean.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
@Override
public void afterPropertiesSet() {
       super.afterPropertiesSet();
	//Now look for any custom configuration.
   	CacheManager cm = (CacheManager) this.getObject();
   	if (cm != null) {
   		String cacheNames[]= cm.getCacheNames();

   		//Check for old configuration properties.
   		for (String cacheName:cacheNames) {
   			if(serverConfigurationService.getString(cacheName) == null) {
   				log.warn("Old cache configuration "+ cacheName+ " must be changed to memory."+ cacheName);
   			}
   			String config = serverConfigurationService.getString("memory."+ cacheName);
   			if (config != null && config.length() > 0) {
   				log.info("Found configuration override for cache: "+ cacheName+ " of: "+ config);
   				Cache cache = cm.getCache(cacheName);
   				if (cache != null) {
   					new CacheInitializer().configure(config).initialize(cache.getCacheConfiguration());
   				}
   			}
   		}
   	}
   }
 
Example 11
Source File: EhcacheFactory.java    From springboot-admin with Apache License 2.0 6 votes vote down vote up
static Cache getOrAddCache(String cacheName) {
	CacheManager cacheManager = getCacheManager();
	Cache cache = cacheManager.getCache(cacheName);
	if (cache == null) {
		synchronized(locker) {
			cache = cacheManager.getCache(cacheName);
			if (cache == null) {
				log.warn("无法找到缓存 [" + cacheName + "]的配置, 使用默认配置.");
				cacheManager.addCacheIfAbsent(cacheName);
				cache = cacheManager.getCache(cacheName);
				log.debug("缓存 [" + cacheName + "] 启动.");
			}
		}
	}
	return cache;
}
 
Example 12
Source File: EnchachePooFactory.java    From Mycat2 with GNU General Public License v3.0 6 votes vote down vote up
@Override
public CachePool createCachePool(String poolName, int cacheSize,
		int expiredSeconds) {
	CacheManager cacheManager = CacheManager.create();
	Cache enCache = cacheManager.getCache(poolName);
	if (enCache == null) {

		CacheConfiguration cacheConf = cacheManager.getConfiguration()
				.getDefaultCacheConfiguration().clone();
		cacheConf.setName(poolName);
		if (cacheConf.getMaxEntriesLocalHeap() != 0) {
			cacheConf.setMaxEntriesLocalHeap(cacheSize);
		} else {
			cacheConf.setMaxBytesLocalHeap(String.valueOf(cacheSize));
		}
		cacheConf.setTimeToIdleSeconds(expiredSeconds);
		Cache cache = new Cache(cacheConf);
		cacheManager.addCache(cache);
		return new EnchachePool(poolName,cache,cacheSize);
	} else {
		return new EnchachePool(poolName,enCache,cacheSize);
	}
}
 
Example 13
Source File: TestHtmlReport.java    From javamelody with Apache License 2.0 5 votes vote down vote up
/** Test.
 * @throws IOException e */
@Test
public void testCache() throws IOException {
	final String cacheName = "test 1";
	final CacheManager cacheManager = CacheManager.getInstance();
	cacheManager.addCache(cacheName);
	// test empty cache name in the cache keys link:
	// cacheManager.addCache("") does nothing, but cacheManager.addCache(new Cache("", ...)) works
	cacheManager.addCache(new Cache("", 1000, true, false, 10000, 10000, false, 10000));
	final String cacheName2 = "test 2";
	try {
		final Cache cache = cacheManager.getCache(cacheName);
		cache.put(new Element(1, Math.random()));
		cache.get(1);
		cache.get(0);
		cacheManager.addCache(cacheName2);
		final Cache cache2 = cacheManager.getCache(cacheName2);
		cache2.getCacheConfiguration().setOverflowToDisk(false);
		cache2.getCacheConfiguration().setEternal(true);
		cache2.getCacheConfiguration().setMaxElementsInMemory(0);

		// JavaInformations doit être réinstancié pour récupérer les caches
		final List<JavaInformations> javaInformationsList2 = Collections
				.singletonList(new JavaInformations(null, true));
		final HtmlReport htmlReport = new HtmlReport(collector, null, javaInformationsList2,
				Period.TOUT, writer);
		htmlReport.toHtml(null, null);
		assertNotEmptyAndClear(writer);
		setProperty(Parameter.SYSTEM_ACTIONS_ENABLED, "false");
		htmlReport.toHtml(null, null);
		assertNotEmptyAndClear(writer);
	} finally {
		setProperty(Parameter.SYSTEM_ACTIONS_ENABLED, null);
		cacheManager.removeCache(cacheName);
		cacheManager.removeCache(cacheName2);
	}
}
 
Example 14
Source File: CacheUtil.java    From ml-blog with MIT License 5 votes vote down vote up
public static void deleteAll() {
    CacheManager cacheManager = SpringContext.getBeanByType(CacheManager.class);
    String[] cacheNames = cacheManager.getCacheNames();
    for (String cacheName : cacheNames) {
        Cache cache = cacheManager.getCache(cacheName);
        cache.removeAll();
        cache.flush();
    }
}
 
Example 15
Source File: EhCacheUtil.java    From zheng with MIT License 5 votes vote down vote up
/**
 * 获取缓存
 * @param cacheName
 * @return
 */
private static Cache getCache(String cacheName) {
    CacheManager cacheManager = CacheManager.getInstance();
    if (null == cacheManager) {
        return null;
    }
    Cache cache = cacheManager.getCache(cacheName);
    if (null == cache) {
        return null;
    }
    return cache;
}
 
Example 16
Source File: SubscriptionsCacheConfiguration.java    From gravitee-gateway with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example 17
Source File: EhCacheBackedMapImpl.java    From openregistry with Apache License 2.0 5 votes vote down vote up
public EhCacheBackedMapImpl() {
    final CacheManager cacheManager = CacheManager.getInstance();
    final Cache tempCache = cacheManager.getCache(DEFAULT_CACHE_NAME);

    if (tempCache == null) {
        this.cache = new Cache(DEFAULT_CACHE_NAME, 20000, false, false, 60000, 60000);
        cacheManager.addCache(this.cache);
    } else {
        this.cache = tempCache;
    }
}
 
Example 18
Source File: CacheUtil.java    From ml-blog with MIT License 4 votes vote down vote up
public static void deleteByName(String cacheName) {
    CacheManager cacheManager = SpringContext.getBeanByType(CacheManager.class);
    Cache cache = cacheManager.getCache(cacheName);
    cache.removeAll();
    cache.flush();
}
 
Example 19
Source File: EhcacheTest.java    From blog with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public static void main(String[] args) {
	try {

		// 创建一个CacheManager实例
		CacheManager manager = new CacheManager();
		// 增加一个cache
		manager.addCache("cardCache");
		// 获取所有cache名称
		String[] cacheNamesForManager = manager.getCacheNames();
		int iLen = cacheNamesForManager.length;
		System.out.println("缓存名称列表:----------------------------");
		for (int i = 0; i < iLen; i++) {
			System.out.println(cacheNamesForManager[i].toString());
		}

		// 获取cache对象
		Cache cache = manager.getCache("cardCache");
		// create
		Element element = new Element("username", "howsky");
		cache.put(element);

		// get
		Element element_get = cache.get("username");
		Object value = element_get.getObjectValue();
		System.out.println(value.toString());
		
		Element element_get2 = cache.get("username");
		System.out.println(element_get2==element_get);

		// update
		cache.put(new Element("username", "howsky.net"));
		// get
		Element element_new = cache.get("username");
		
		System.out.println(element_new==element_get);
		
		Object value_new = element_new.getObjectValue();
		System.out.println(value_new.toString());

		cache.remove("username");

		// 移除cache
		manager.removeCache("cardCache");

		// 关闭CacheManager
		manager.shutdown();

	} catch (Exception e) {

		System.out.println(e.getMessage());

	}
}
 
Example 20
Source File: EhcacheApiTest.java    From spring-tutorial with Creative Commons Attribution Share Alike 4.0 International 4 votes vote down vote up
/**
 * 使用Ehcache默认配置(classpath下的ehcache.xml)获取单例的CacheManager实例
 */
@Test
public void operation() {
	CacheManager manager = CacheManager.newInstance("src/test/resources/ehcache/ehcache.xml");

	// 获得Cache的引用
	Cache cache = manager.getCache("users");

	// 将一个Element添加到Cache
	cache.put(new Element("key1", "value1"));

	// 获取Element,Element类支持序列化,所以下面两种方法都可以用
	Element element1 = cache.get("key1");
	// 获取非序列化的值
	System.out.println("key=" + element1.getObjectKey() + ", value=" + element1.getObjectValue());
	// 获取序列化的值
	System.out.println("key=" + element1.getKey() + ", value=" + element1.getValue());

	// 更新Cache中的Element
	cache.put(new Element("key1", "value2"));
	Element element2 = cache.get("key1");
	System.out.println("key=" + element2.getObjectKey() + ", value=" + element2.getObjectValue());

	// 获取Cache的元素数
	System.out.println("cache size:" + cache.getSize());

	// 获取MemoryStore的元素数
	System.out.println("MemoryStoreSize:" + cache.getMemoryStoreSize());

	// 获取DiskStore的元素数
	System.out.println("DiskStoreSize:" + cache.getDiskStoreSize());

	// 移除Element
	cache.remove("key1");
	System.out.println("cache size:" + cache.getSize());

	// 关闭当前CacheManager对象
	manager.shutdown();

	// 关闭CacheManager单例实例
	CacheManager.getInstance().shutdown();
}