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

The following examples show how to use net.sf.ehcache.CacheManager#addCache() . 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 6 votes vote down vote up
public ResourceFactoryCache createFactoryCache() {
  try {
    final CacheManager manager = getCacheManager();
    synchronized( manager ) {
      if ( manager.cacheExists( FACTORY_CACHE_NAME ) == false ) {
        final Cache libloaderCache = new Cache( FACTORY_CACHE_NAME,   // cache name
          500,         // maxElementsInMemory
          false,       // overflowToDisk
          false,       // eternal
          600,         // timeToLiveSeconds
          600,         // timeToIdleSeconds
          false,       // diskPersistent
          120 );        // diskExpiryThreadIntervalSeconds
        manager.addCache( libloaderCache );
        return new EHResourceFactoryCache( libloaderCache );
      } else {
        return new EHResourceFactoryCache( manager.getCache( FACTORY_CACHE_NAME ) );
      }
    }
  } catch ( CacheException e ) {
    logger.debug( "Failed to create EHCache libloader-factory cache", e );
    return null;
  }
}
 
Example 2
Source File: EHCacheProvider.java    From pentaho-reporting with GNU Lesser General Public License v2.1 6 votes vote down vote up
public ResourceBundleDataCache createBundleDataCache() {
  try {
    final CacheManager manager = getCacheManager();
    synchronized( manager ) {
      if ( manager.cacheExists( BUNDLES_CACHE_NAME ) == false ) {
        final Cache libloaderCache = new Cache( BUNDLES_CACHE_NAME,   // cache name
          500,         // maxElementsInMemory
          false,       // overflowToDisk
          false,       // eternal
          600,         // timeToLiveSeconds
          600,         // timeToIdleSeconds
          false,       // diskPersistent
          120 );        // diskExpiryThreadIntervalSeconds
        manager.addCache( libloaderCache );
        return new EHResourceBundleDataCache( libloaderCache );
      } else {
        return new EHResourceBundleDataCache( manager.getCache( BUNDLES_CACHE_NAME ) );
      }
    }
  } catch ( CacheException e ) {
    logger.debug( "Failed to create EHCache libloader-bundles cache", e );
    return null;
  }
}
 
Example 3
Source File: TicketRegistryDecoratorTests.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
@Test
public void verifyEhCacheTicketRegistryWithClearPass() {
    final Cache serviceTicketsCache = new Cache("serviceTicketsCache", 200, false, false, 100, 100);
    final Cache ticketGrantingTicketCache = new Cache("ticketGrantingTicketCache", 200, false, false, 100, 100);

    final CacheManager manager = new CacheManager(this.getClass().getClassLoader().getResourceAsStream("ehcacheClearPass.xml"));
    manager.addCache(serviceTicketsCache);
    manager.addCache(ticketGrantingTicketCache);

    final Map<String, String> map = new HashMap<>();

    final TicketRegistry ticketRegistry = new EhCacheTicketRegistry(serviceTicketsCache, ticketGrantingTicketCache);
    final TicketRegistryDecorator decorator = new TicketRegistryDecorator(ticketRegistry, map);
    assertNotNull(decorator);

    assertEquals(decorator.serviceTicketCount(), 0);
    assertEquals(decorator.sessionCount(), 0);

    manager.removalAll();
    manager.shutdown();

}
 
Example 4
Source File: TicketRegistryDecoratorTests.java    From cas4.0.x-server-wechat with Apache License 2.0 6 votes vote down vote up
@Test
public void testEhCacheTicketRegistryWithClearPass() {
    final Cache serviceTicketsCache = new Cache("serviceTicketsCache", 200, false, false, 100, 100);
    final Cache ticketGrantingTicketCache = new Cache("ticketGrantingTicketCache", 200, false, false, 100, 100);

    final CacheManager manager = new CacheManager(this.getClass().getClassLoader().getResourceAsStream("ehcacheClearPass.xml"));
    manager.addCache(serviceTicketsCache);
    manager.addCache(ticketGrantingTicketCache);

    final Map<String, String> map = new HashMap<String, String>();

    final TicketRegistry ticketRegistry = new EhCacheTicketRegistry(serviceTicketsCache, ticketGrantingTicketCache);
    final TicketRegistryDecorator decorator = new TicketRegistryDecorator(ticketRegistry, map);
    assertNotNull(decorator);

    assertEquals(decorator.serviceTicketCount(), 0);
    assertEquals(decorator.sessionCount(), 0);

    manager.removalAll();
    manager.shutdown();

}
 
Example 5
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 6
Source File: EnchachePooFactory.java    From dble with GNU General Public License v2.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 7
Source File: EhcacheApiTest.java    From spring-tutorial with Creative Commons Attribution Share Alike 4.0 International 6 votes vote down vote up
/**
 * 使用特定的配置添加缓存
 */
@Test
public void addAndRemove03() {
	CacheManager manager = CacheManager.create();

	// 添加缓存
	Cache testCache = new Cache(new CacheConfiguration("testCache3", 5000)
		.memoryStoreEvictionPolicy(MemoryStoreEvictionPolicy.LFU).eternal(false).timeToLiveSeconds(60)
		.timeToIdleSeconds(30).diskExpiryThreadIntervalSeconds(0)
		.persistence(new PersistenceConfiguration().strategy(PersistenceConfiguration.Strategy.LOCALTEMPSWAP)));
	manager.addCache(testCache);

	// 打印配置信息和状态
	Cache test = manager.getCache("testCache3");
	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());

	// 删除缓存
	manager.removeCache("testCache3");
	System.out.println("cache status:" + test.getStatus().toString());
}
 
Example 8
Source File: GenericDaoBase.java    From cosmic with Apache License 2.0 6 votes vote down vote up
@DB()
protected void createCache(final Map<String, ? extends Object> params) {
    final String value = (String) params.get("cache.size");

    if (value != null) {
        final CacheManager cm = CacheManager.create();
        final int maxElements = NumbersUtil.parseInt(value, 0);
        final int live = NumbersUtil.parseInt((String) params.get("cache.time.to.live"), 300);
        final int idle = NumbersUtil.parseInt((String) params.get("cache.time.to.idle"), 300);
        _cache = new Cache(getName(), maxElements, false, live == -1, live == -1 ? Integer.MAX_VALUE : live, idle);
        cm.addCache(_cache);
        s_logger.info("Cache created: " + _cache.toString());
    } else {
        _cache = null;
    }
}
 
Example 9
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 10
Source File: EhCacheCacheTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
	cacheManager = new CacheManager(new Configuration().name("EhCacheCacheTests")
			.defaultCache(new CacheConfiguration("default", 100)));
	nativeCache = new net.sf.ehcache.Cache(new CacheConfiguration(CACHE_NAME, 100));
	cacheManager.addCache(nativeCache);

	cache = new EhCacheCache(nativeCache);
}
 
Example 11
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 12
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 13
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 14
Source File: ApiKeysCacheConfiguration.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(API_KEY_CACHE_NAME);
    if (apiKeyCache == null) {
        LOGGER.warn("EHCache cache for apikey not found. Fallback to default EHCache configuration");
        CacheConfiguration cacheConfiguration = new CacheConfiguration(API_KEY_CACHE_NAME, 1000);
        cacheManager.addCache(new Cache(cacheConfiguration));
    }

    return cacheManager.getCache(API_KEY_CACHE_NAME);
}
 
Example 15
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 16
Source File: ApiRateLimitServiceImpl.java    From cosmic with Apache License 2.0 5 votes vote down vote up
@Override
public boolean configure(final String name, final Map<String, Object> params) throws ConfigurationException {
    super.configure(name, params);

    if (_store == null) {
        // get global configured duration and max values
        final String isEnabled = _configDao.getValue(Config.ApiLimitEnabled.key());
        if (isEnabled != null) {
            enabled = Boolean.parseBoolean(isEnabled);
        }
        final String duration = _configDao.getValue(Config.ApiLimitInterval.key());
        if (duration != null) {
            timeToLive = Integer.parseInt(duration);
        }
        final String maxReqs = _configDao.getValue(Config.ApiLimitMax.key());
        if (maxReqs != null) {
            maxAllowed = Integer.parseInt(maxReqs);
        }
        // create limit store
        final EhcacheLimitStore cacheStore = new EhcacheLimitStore();
        int maxElements = 10000;
        final String cachesize = _configDao.getValue(Config.ApiLimitCacheSize.key());
        if (cachesize != null) {
            maxElements = Integer.parseInt(cachesize);
        }
        final CacheManager cm = CacheManager.create();
        final Cache cache = new Cache("api-limit-cache", maxElements, false, false, timeToLive, timeToLive);
        cm.addCache(cache);
        s_logger.info("Limit Cache created with timeToLive=" + timeToLive + ", maxAllowed=" + maxAllowed + ", maxElements=" + maxElements);
        cacheStore.setCache(cache);
        _store = cacheStore;
    }

    return true;
}
 
Example 17
Source File: EhCacheCacheTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Before
public void setup() {
	cacheManager = new CacheManager(new Configuration().name("EhCacheCacheTests")
			.defaultCache(new CacheConfiguration("default", 100)));
	nativeCache = new net.sf.ehcache.Cache(new CacheConfiguration(CACHE_NAME, 100));
	cacheManager.addCache(nativeCache);

	cache = new EhCacheCache(nativeCache);
}
 
Example 18
Source File: EhcacheCacheStorage.java    From esigate with Apache License 2.0 5 votes vote down vote up
@Override
public void init(Properties properties) {
    String cacheName = Parameters.EHCACHE_CACHE_NAME_PROPERTY.getValue(properties);
    String configurationFileName = Parameters.EHCACHE_CONFIGURATION_FILE_PROPERTY.getValue(properties);
    // Loaded from the Classpath, default will use /ehcache.xml or if not found /ehcache-failsafe.xml
    CacheManager cacheManager = CacheManager.create(configurationFileName);
    Ehcache ehcache = cacheManager.getEhcache(cacheName);
    if (ehcache == null) {
        cacheManager.addCache(cacheName);
        ehcache = cacheManager.getEhcache(cacheName);
    }
    CacheConfig cacheConfig = CacheConfigHelper.createCacheConfig(properties);
    setImpl(new EhcacheHttpCacheStorage(ehcache, cacheConfig));
}
 
Example 19
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 20
Source File: ApiRateLimitServiceImpl.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
@Override
public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
    super.configure(name, params);

    if (_store == null) {
        // get global configured duration and max values
        String isEnabled = _configDao.getValue(Config.ApiLimitEnabled.key());
        if (isEnabled != null) {
            enabled = Boolean.parseBoolean(isEnabled);
        }
        String duration = _configDao.getValue(Config.ApiLimitInterval.key());
        if (duration != null) {
            timeToLive = Integer.parseInt(duration);
        }
        String maxReqs = _configDao.getValue(Config.ApiLimitMax.key());
        if (maxReqs != null) {
            maxAllowed = Integer.parseInt(maxReqs);
        }
        // create limit store
        EhcacheLimitStore cacheStore = new EhcacheLimitStore();
        int maxElements = 10000;
        String cachesize = _configDao.getValue(Config.ApiLimitCacheSize.key());
        if (cachesize != null) {
            maxElements = Integer.parseInt(cachesize);
        }
        CacheManager cm = CacheManager.create();
        Cache cache = new Cache("api-limit-cache", maxElements, false, false, timeToLive, timeToLive);
        cm.addCache(cache);
        s_logger.info("Limit Cache created with timeToLive=" + timeToLive + ", maxAllowed=" + maxAllowed + ", maxElements=" + maxElements);
        cacheStore.setCache(cache);
        _store = cacheStore;

    }

    return true;
}