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

The following examples show how to use net.sf.ehcache.CacheManager#newInstance() . 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: AbstractIntegrationModule.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
private void initCaching() {
   LOG.info("INIT CACHE MANAGER");
   URL url = this.getClass().getResource("/cache/config/ehcache.xml");
   this.cacheManager = CacheManager.newInstance(url);
   LOG.info("DOES KGSS CACHE EXIST?");
   this.kgssCache = this.cacheManager.getCache("KGSS");
   if (this.kgssCache == null) {
      LOG.info("NEW KGSS CACHE");
      this.kgssCache = new Cache("KGSS", 0, false, false, 0L, 0L);
      this.cacheManager.addCache(this.kgssCache);
   }

   LOG.info("DOES ETK CACHE EXIST?");
   this.etkCache = this.cacheManager.getCache("ETK");
   if (this.etkCache == null) {
      LOG.info("NEW ETK CACHE");
      this.etkCache = new Cache("ETK", 0, false, false, 0L, 0L);
      this.cacheManager.addCache(this.etkCache);
   }

}
 
Example 2
Source File: EhCacheProvider.java    From J2Cache with Apache License 2.0 6 votes vote down vote up
/**
 * init ehcache config
 *
 * @param props current configuration settings.
 */
public void start(Properties props) {
    if (manager != null) {
        log.warn("Attempt to restart an already started EhCacheProvider.");
        return;
    }

    // 如果指定了名称,那么尝试获取已有实例
    String ehcacheName = (String)props.get(KEY_EHCACHE_NAME);
    if (ehcacheName != null && ehcacheName.trim().length() > 0)
        manager = CacheManager.getCacheManager(ehcacheName);
    if (manager == null) {
        // 指定了配置文件路径? 加载之
        if (props.containsKey(KEY_EHCACHE_CONFIG_XML)) {
            String propertiesFile = props.getProperty(KEY_EHCACHE_CONFIG_XML);
            URL url = getClass().getResource(propertiesFile);
            url = (url == null) ? getClass().getClassLoader().getResource(propertiesFile) : url;
            manager = CacheManager.newInstance(url);
        } else {
            // 加载默认实例
            manager = CacheManager.getInstance();
        }
    }
    caches = new ConcurrentHashMap<>();
}
 
Example 3
Source File: EhCache2MetricsTest.java    From micrometer with Apache License 2.0 5 votes vote down vote up
@BeforeAll
static void setup() {
    cacheManager = CacheManager.newInstance();
    cacheManager.addCache("testCache");
    cache = spy(cacheManager.getCache("testCache"));
    StatisticsGateway stats = mock(StatisticsGateway.class);
    // generate non-negative random value to address false-positives
    int valueBound = 100000;
    Random random = new Random();
    when(stats.getSize()).thenReturn((long) random.nextInt(valueBound));
    when(stats.cacheEvictedCount()).thenReturn((long) random.nextInt(valueBound));
    when(stats.cacheHitCount()).thenReturn((long) random.nextInt(valueBound));
    when(stats.cacheMissCount()).thenReturn((long) random.nextInt(valueBound));
    when(stats.cachePutCount()).thenReturn((long) random.nextInt(valueBound));
    when(stats.getRemoteSize()).thenReturn((long) random.nextInt(valueBound));
    when(stats.cacheRemoveCount()).thenReturn((long) random.nextInt(valueBound));
    when(stats.cachePutAddedCount()).thenReturn((long) random.nextInt(valueBound));
    when(stats.cachePutUpdatedCount()).thenReturn((long) random.nextInt(valueBound));
    when(stats.getLocalOffHeapSizeInBytes()).thenReturn((long) random.nextInt(valueBound));
    when(stats.getLocalHeapSizeInBytes()).thenReturn((long) random.nextInt(valueBound));
    when(stats.getLocalDiskSizeInBytes()).thenReturn((long) random.nextInt(valueBound));
    when(stats.cacheMissExpiredCount()).thenReturn((long) random.nextInt(valueBound));
    when(stats.cacheMissNotFoundCount()).thenReturn((long) random.nextInt(valueBound));
    when(stats.xaCommitCommittedCount()).thenReturn((long) random.nextInt(valueBound));
    when(stats.xaCommitExceptionCount()).thenReturn((long) random.nextInt(valueBound));
    when(stats.xaCommitReadOnlyCount()).thenReturn((long) random.nextInt(valueBound));
    when(stats.xaRollbackExceptionCount()).thenReturn((long) random.nextInt(valueBound));
    when(stats.xaRollbackSuccessCount()).thenReturn((long) random.nextInt(valueBound));
    when(stats.xaRecoveryRecoveredCount()).thenReturn((long) random.nextInt(valueBound));
    when(stats.xaRecoveryNothingCount()).thenReturn((long) random.nextInt(valueBound));
    when(cache.getStatistics()).thenReturn(stats);
}
 
Example 4
Source File: EhCache2MetricsCompatibilityTest.java    From micrometer with Apache License 2.0 5 votes vote down vote up
EhCache2MetricsCompatibilityTest() {
    Configuration config = ConfigurationFactory.parseConfiguration();
    config.setName(UUID.randomUUID().toString());

    this.cacheManager = CacheManager.newInstance(config);
    this.cacheManager.addCache("mycache");
    this.cache = cacheManager.getCache("mycache");
}
 
Example 5
Source File: EhcacheApiTest.java    From spring-tutorial with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
/**
 * 使用Ehcache默认配置(classpath下的ehcache.xml)新建一个单例的CacheManager实例
 */
@Test
public void create02() {
	CacheManager.newInstance();

	String[] cacheNames = CacheManager.getInstance().getCacheNames();
	for (String name : cacheNames) {
		System.out.println("name:" + name);
	}
}
 
Example 6
Source File: EhcacheApiTest.java    From spring-tutorial with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
/**
 * 基于classpath下的配置文件创建CacheManager实例
 */
@Test
public void create04() {
	URL url = getClass().getResource("/cache/ehcache.xml");
	CacheManager manager = CacheManager.newInstance(url);
	String[] cacheNames = manager.getCacheNames();

	for (String name : cacheNames) {
		System.out.println("[ehcache.xml]name:" + name);
	}
}
 
Example 7
Source File: EhcacheApiTest.java    From spring-tutorial with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
/**
 * 基于IO流得到配置文件,并创建CacheManager实例
 */
@Test
public void create05() throws Exception {
	InputStream fis = new FileInputStream(new File("src/test/resources/ehcache/ehcache.xml").getAbsolutePath());
	CacheManager manager = CacheManager.newInstance(fis);
	fis.close();
	String[] cacheNames = manager.getCacheNames();

	for (String name : cacheNames) {
		System.out.println("[ehcache.xml]name:" + name);
	}
}
 
Example 8
Source File: ApiKeysCacheConfiguration.java    From gravitee-gateway with Apache License 2.0 5 votes vote down vote up
@Bean
public CacheManager cacheManager() {
    String graviteeHome = System.getProperty("gravitee.home");
    String ehCacheConfiguration = graviteeHome + File.separator + "config" + File.separator + "ehcache.xml";

    LOGGER.info("Loading EHCache configuration from {}", ehCacheConfiguration);
    File ehCacheConfigurationFile = new File(ehCacheConfiguration);
    if (ehCacheConfigurationFile.exists()) {
        return CacheManager.newInstance(ehCacheConfigurationFile.getAbsolutePath());
    }

    LOGGER.warn("No configuration file can be found for EHCache");
    throw new IllegalStateException("No configuration file can be found for EHCache");
}
 
Example 9
Source File: SubscriptionsCacheConfiguration.java    From gravitee-gateway with Apache License 2.0 5 votes vote down vote up
@Bean
public CacheManager cacheManager() {
    String graviteeHome = System.getProperty("gravitee.home");
    String ehCacheConfiguration = graviteeHome + File.separator + "config" + File.separator + "ehcache.xml";

    LOGGER.info("Loading EHCache configuration from {}", ehCacheConfiguration);
    File ehCacheConfigurationFile = new File(ehCacheConfiguration);
    if (ehCacheConfigurationFile.exists()) {
        return CacheManager.newInstance(ehCacheConfigurationFile.getAbsolutePath());
    }

    LOGGER.warn("No configuration file can be found for EHCache");
    throw new IllegalStateException("No configuration file can be found for EHCache");
}
 
Example 10
Source File: PipelineSqlMapDao.java    From gocd with Apache License 2.0 5 votes vote down vote up
private static Ehcache createCacheIfRequired(String cacheName) {
    final CacheManager instance = CacheManager.newInstance(new Configuration().name(cacheName));
    synchronized (instance) {
        if (!instance.cacheExists(cacheName)) {
            instance.addCache(new Cache(cacheConfiguration(cacheName)));
        }
        return instance.getCache(cacheName);
    }
}
 
Example 11
Source File: JobInstanceSqlMapDao.java    From gocd with Apache License 2.0 5 votes vote down vote up
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);
    }
}
 
Example 12
Source File: GoCacheFactory.java    From gocd with Apache License 2.0 5 votes vote down vote up
@Bean(name = "goCache")
public GoCache createCache() {
    CacheManager cacheManager = CacheManager.newInstance(new Configuration().name(getClass().getName()));
    Cache cache = new Cache(cacheConfiguration);
    cacheManager.addCache(cache);
    return new GoCache(cache, transactionSynchronizationManager);
}
 
Example 13
Source File: EhcacheModule.java    From joynr with Apache License 2.0 5 votes vote down vote up
@Provides
@Singleton
CacheManager getCacheManager(@Named(BounceProxyEhcacheAdapter.PROPERTY_BP_CACHE_CONFIGURATION) String cacheConfigFileName) {

    log.info("Using ehcache config file: {}", cacheConfigFileName);
    URL cacheConfigFileUrl = getClass().getResource("/" + cacheConfigFileName);
    if (cacheConfigFileUrl == null) {
        log.error("No resource with filename found on classpath: {}. Using default CacheManager",
                  cacheConfigFileName);
        return CacheManager.newInstance();
    } else {
        return CacheManager.newInstance(cacheConfigFileUrl);
    }
}
 
Example 14
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();
}
 
Example 15
Source File: GoCacheTest.java    From gocd with Apache License 2.0 4 votes vote down vote up
@BeforeClass
public static void beforeClass() {
    cacheManager = CacheManager.newInstance(new Configuration().name(GoCacheTest.class.getName()));
}
 
Example 16
Source File: ClusteredBounceProxyControllerTest.java    From joynr with Apache License 2.0 4 votes vote down vote up
private void waitForCachesJoiningCluster() throws InterruptedException {
    CacheManager cacheManager = CacheManager.newInstance(getClass().getResource("/ehcache_distributed_test.xml"));

    CacheManagerPeerProvider peerProvider = cacheManager.getCacheManagerPeerProvider("RMI");

    int peers = 0;
    long timeoutMs = 10000;
    long startMs = System.currentTimeMillis();
    do {
        Thread.sleep(1000);

        peers = peerProvider.listRemoteCachePeers(cacheManager.getEhcache("bpCache1")).size();

    } while (peers < 2 && (System.currentTimeMillis() - startMs < timeoutMs));

    Assert.assertEquals(2, peers);

    cacheManager.shutdown();
}