net.sf.ehcache.config.CacheConfiguration Java Examples

The following examples show how to use net.sf.ehcache.config.CacheConfiguration. 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: EhCacheTicketRegistry.java    From cas4.0.x-server-wechat with Apache License 2.0 6 votes vote down vote up
@Override
public void afterPropertiesSet() throws Exception {
    if (this.serviceTicketsCache == null || this.ticketGrantingTicketsCache == null) {
        throw new BeanInstantiationException(this.getClass(),
                "Both serviceTicketsCache and ticketGrantingTicketsCache are required properties.");
    }

    if (logger.isDebugEnabled()) {
        CacheConfiguration config = this.serviceTicketsCache.getCacheConfiguration();
        logger.debug("serviceTicketsCache.maxElementsInMemory={}", config.getMaxEntriesLocalHeap());
        logger.debug("serviceTicketsCache.maxElementsOnDisk={}", config.getMaxElementsOnDisk());
        logger.debug("serviceTicketsCache.isOverflowToDisk={}", config.isOverflowToDisk());
        logger.debug("serviceTicketsCache.timeToLive={}", config.getTimeToLiveSeconds());
        logger.debug("serviceTicketsCache.timeToIdle={}", config.getTimeToIdleSeconds());
        logger.debug("serviceTicketsCache.cacheManager={}", this.serviceTicketsCache.getCacheManager().getName());

        config = this.ticketGrantingTicketsCache.getCacheConfiguration();
        logger.debug("ticketGrantingTicketsCache.maxElementsInMemory={}", config.getMaxEntriesLocalHeap());
        logger.debug("ticketGrantingTicketsCache.maxElementsOnDisk={}", config.getMaxElementsOnDisk());
        logger.debug("ticketGrantingTicketsCache.isOverflowToDisk={}", config.isOverflowToDisk());
        logger.debug("ticketGrantingTicketsCache.timeToLive={}", config.getTimeToLiveSeconds());
        logger.debug("ticketGrantingTicketsCache.timeToIdle={}", config.getTimeToIdleSeconds());
        logger.debug("ticketGrantingTicketsCache.cacheManager={}", this.ticketGrantingTicketsCache.getCacheManager()
                .getName());
    }
}
 
Example #2
Source File: EhCacheFactory.java    From nextreports-server with Apache License 2.0 6 votes vote down vote up
protected void createCache(String name, int expirationTime) {
		synchronized (this.getClass()) {
			cacheManager.addCache(name);

			Ehcache cache = cacheManager.getEhcache(name);
			CacheConfiguration config = cache.getCacheConfiguration();
			config.setEternal(false);
			config.setTimeToLiveSeconds(expirationTime);
//		    config.setTimeToIdleSeconds(60);
//		    config.setMaxElementsInMemory(10000);
//		    config.setMaxElementsOnDisk(1000000);
		    
			BlockingCache blockingCache = new BlockingCache(cache);
			cacheManager.replaceCacheWithDecoratedCache(cache, blockingCache);
		}
	}
 
Example #3
Source File: DaoSpringModuleConfig.java    From herd with Apache License 2.0 6 votes vote down vote up
/**
 * Gets an EH Cache manager.
 *
 * @return the EH Cache manager.
 */
@Bean(destroyMethod = "shutdown")
public net.sf.ehcache.CacheManager ehCacheManager()
{
    CacheConfiguration cacheConfiguration = new CacheConfiguration();
    cacheConfiguration.setName(HERD_CACHE_NAME);
    cacheConfiguration.setTimeToLiveSeconds(configurationHelper.getProperty(ConfigurationValue.HERD_CACHE_TIME_TO_LIVE_SECONDS, Long.class));
    cacheConfiguration.setTimeToIdleSeconds(configurationHelper.getProperty(ConfigurationValue.HERD_CACHE_TIME_TO_IDLE_SECONDS, Long.class));
    cacheConfiguration.setMaxElementsInMemory(configurationHelper.getProperty(ConfigurationValue.HERD_CACHE_MAX_ELEMENTS_IN_MEMORY, Integer.class));
    cacheConfiguration.setMemoryStoreEvictionPolicy(configurationHelper.getProperty(ConfigurationValue.HERD_CACHE_MEMORY_STORE_EVICTION_POLICY));

    net.sf.ehcache.config.Configuration config = new net.sf.ehcache.config.Configuration();
    config.addCache(cacheConfiguration);

    return net.sf.ehcache.CacheManager.create(config);
}
 
Example #4
Source File: EhcacheManager.java    From jpress with GNU Lesser General Public License v3.0 6 votes vote down vote up
public static void init() {

        Configuration config = ConfigurationFactory.parseConfiguration();
        config.setClassLoader(ehcacheClassloader);

        String maxBytesLocalHeap = JbootConfigManager.me().getConfigValue("jpress.ehcache.maxBytesLocalHeap");
        config.setMaxBytesLocalHeap(StrUtil.obtainDefaultIfBlank(maxBytesLocalHeap, "100M"));

        String maxBytesLocalDisk = JbootConfigManager.me().getConfigValue("jpress.ehcache.maxBytesLocalDisk");
        config.setMaxBytesLocalDisk(StrUtil.obtainDefaultIfBlank(maxBytesLocalDisk, "5G"));

        CacheConfiguration cacheConfiguration = new CacheConfiguration();
        cacheConfiguration.setClassLoader(ehcacheClassloader);
        config.defaultCache(cacheConfiguration);

        CacheManager.create(config);
    }
 
Example #5
Source File: EhCacheProvider.java    From J2Cache with Apache License 2.0 6 votes vote down vote up
@Override
public EhCache buildCache(String region, long timeToLiveInSeconds, CacheExpiredListener listener) {
    EhCache ehcache = caches.computeIfAbsent(region, v -> {
        //配置缓存
        CacheConfiguration cfg = manager.getConfiguration().getDefaultCacheConfiguration().clone();
        cfg.setName(region);
        if(timeToLiveInSeconds > 0) {
            cfg.setTimeToLiveSeconds(timeToLiveInSeconds);
            cfg.setTimeToIdleSeconds(timeToLiveInSeconds);
        }

        net.sf.ehcache.Cache cache = new net.sf.ehcache.Cache(cfg);
        manager.addCache(cache);

        log.info("Started Ehcache region [{}] with TTL: {}", region, timeToLiveInSeconds);

        return new EhCache(cache, listener);
    });

    if (ehcache.ttl() != timeToLiveInSeconds)
        throw new IllegalArgumentException(String.format("Region [%s] TTL %d not match with %d", region, ehcache.ttl(), timeToLiveInSeconds));

    return ehcache;
}
 
Example #6
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 #7
Source File: CachedParentLdapGroupAuthorityRetrieverTest.java    From hesperides with GNU General Public License v3.0 6 votes vote down vote up
@Before
public void setUp() {
    parentGroupsTree = new HashMap<>();
    cache = new Cache(new CacheConfiguration(TEST_GROUPS_TREE_CACHE_NAME, 5000)
            .memoryStoreEvictionPolicy(MemoryStoreEvictionPolicy.LFU)
            .timeToLiveSeconds(2)
            .diskPersistent(false)
            .eternal(false)
            .overflowToDisk(false));
    if (cacheManager.cacheExists(TEST_GROUPS_TREE_CACHE_NAME)) {
        cacheManager.removeCache(TEST_GROUPS_TREE_CACHE_NAME);
    }
    cacheManager.addCache(cache);
    cachedParentLdapGroupAuthorityRetriever = new CachedParentLdapGroupAuthorityRetriever(cache);
    cachedParentLdapGroupAuthorityRetriever.setParentGroupsDNRetriever(dn ->
            parentGroupsTree.getOrDefault(dn, new HashSet<>())
    );
}
 
Example #8
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 #9
Source File: EhCacheTicketRegistry.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
@Override
public void afterPropertiesSet() throws Exception {
    if (this.serviceTicketsCache == null || this.ticketGrantingTicketsCache == null) {
        throw new BeanInstantiationException(this.getClass(),
                "Both serviceTicketsCache and ticketGrantingTicketsCache are required properties.");
    }

    if (logger.isDebugEnabled()) {
        CacheConfiguration config = this.serviceTicketsCache.getCacheConfiguration();
        logger.debug("serviceTicketsCache.maxElementsInMemory={}", config.getMaxEntriesLocalHeap());
        logger.debug("serviceTicketsCache.maxElementsOnDisk={}", config.getMaxElementsOnDisk());
        logger.debug("serviceTicketsCache.isOverflowToDisk={}", config.isOverflowToDisk());
        logger.debug("serviceTicketsCache.timeToLive={}", config.getTimeToLiveSeconds());
        logger.debug("serviceTicketsCache.timeToIdle={}", config.getTimeToIdleSeconds());
        logger.debug("serviceTicketsCache.cacheManager={}", this.serviceTicketsCache.getCacheManager().getName());

        config = this.ticketGrantingTicketsCache.getCacheConfiguration();
        logger.debug("ticketGrantingTicketsCache.maxElementsInMemory={}", config.getMaxEntriesLocalHeap());
        logger.debug("ticketGrantingTicketsCache.maxElementsOnDisk={}", config.getMaxElementsOnDisk());
        logger.debug("ticketGrantingTicketsCache.isOverflowToDisk={}", config.isOverflowToDisk());
        logger.debug("ticketGrantingTicketsCache.timeToLive={}", config.getTimeToLiveSeconds());
        logger.debug("ticketGrantingTicketsCache.timeToIdle={}", config.getTimeToIdleSeconds());
        logger.debug("ticketGrantingTicketsCache.cacheManager={}", this.ticketGrantingTicketsCache.getCacheManager()
                .getName());
    }
}
 
Example #10
Source File: CacheService.java    From lutece-core with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Read cache config from the file caches.dat
 *
 * @param strCacheName
 *            The cache name
 * @return The config
 */
private CacheConfiguration getCacheConfiguration( String strCacheName )
{
    CacheConfiguration config = new CacheConfiguration( );
    config.setName( strCacheName );
    config.setMaxElementsInMemory( getIntProperty( strCacheName, PROPERTY_MAX_ELEMENTS, _nDefaultMaxElementsInMemory ) );
    config.setEternal( getBooleanProperty( strCacheName, PROPERTY_ETERNAL, _bDefaultEternal ) );
    config.setTimeToIdleSeconds( getLongProperty( strCacheName, PROPERTY_TIME_TO_IDLE, _lDefaultTimeToIdle ) );
    config.setTimeToLiveSeconds( getLongProperty( strCacheName, PROPERTY_TIME_TO_LIVE, _lDefaultTimeToLive ) );
    config.setOverflowToDisk( getBooleanProperty( strCacheName, PROPERTY_OVERFLOW_TO_DISK, _bDefaultOverflowToDisk ) );
    config.setDiskPersistent( getBooleanProperty( strCacheName, PROPERTY_DISK_PERSISTENT, _bDefaultDiskPersistent ) );
    config.setDiskExpiryThreadIntervalSeconds( getLongProperty( strCacheName, PROPERTY_DISK_EXPIRY, _lDefaultDiskExpiry ) );
    config.setMaxElementsOnDisk( getIntProperty( strCacheName, PROPERTY_MAX_ELEMENTS_DISK, _nDefaultMaxElementsOnDisk ) );
    config.setStatistics( getBooleanProperty( strCacheName, PROPERTY_STATISTICS, _bDefaultStatistics ) );

    return config;
}
 
Example #11
Source File: AutoCreatingEhCacheCacheManager.java    From find with MIT License 6 votes vote down vote up
@Override
protected Cache getMissingCache(final String name) {
    final Cache missingCache = super.getMissingCache(name);

    if (missingCache == null) {
        final CacheConfiguration cacheConfiguration = defaults.clone().name(name);

        final String cacheName = getCacheName(name);

        if (cacheExpires.containsKey(cacheName)) {
            cacheConfiguration.setTimeToLiveSeconds(cacheExpires.get(cacheName));
        }

        final net.sf.ehcache.Cache ehcache = new net.sf.ehcache.Cache(cacheConfiguration);
        ehcache.initialise();

        return new EhCacheCache(ehcache);
    } else {
        return missingCache;
    }
}
 
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: CacheInformations.java    From javamelody with Apache License 2.0 6 votes vote down vote up
private String buildConfiguration(Object cache) {
	final StringBuilder sb = new StringBuilder();
	// getCacheConfiguration() et getMaxElementsOnDisk() n'existent pas en ehcache 1.2
	final CacheConfiguration config = ((Ehcache) cache).getCacheConfiguration();
	sb.append("ehcache [maxElementsInMemory = ").append(config.getMaxElementsInMemory());
	final boolean overflowToDisk = config.isOverflowToDisk();
	sb.append(", overflowToDisk = ").append(overflowToDisk);
	if (overflowToDisk) {
		sb.append(", maxElementsOnDisk = ").append(config.getMaxElementsOnDisk());
	}
	final boolean eternal = config.isEternal();
	sb.append(", eternal = ").append(eternal);
	if (!eternal) {
		sb.append(", timeToLiveSeconds = ").append(config.getTimeToLiveSeconds());
		sb.append(", timeToIdleSeconds = ").append(config.getTimeToIdleSeconds());
		sb.append(", memoryStoreEvictionPolicy = ")
				.append(config.getMemoryStoreEvictionPolicy());
	}
	sb.append(", diskPersistent = ").append(config.isDiskPersistent());
	sb.append(']');
	return sb.toString();
}
 
Example #14
Source File: CacheDirectorImpl.java    From yes-cart with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public List<CacheInfoDTO> getCacheInfo() {
    final Collection<String> cacheNames = cacheManager.getCacheNames();
    final List<CacheInfoDTO> rez = new ArrayList<>(cacheNames.size());
    for (String cacheName : cacheNames) {
        final Cache cache = cacheManager.getCache(cacheName);
        final net.sf.ehcache.Cache nativeCache = (net.sf.ehcache.Cache) cache.getNativeCache();
        final CacheConfiguration cacheConfiguration = nativeCache.getCacheConfiguration();
        final StatisticsGateway stats = nativeCache.getStatistics();

        rez.add(
                new CacheInfoDTO(
                        nativeCache.getName(),
                        nativeCache.getSize(),
                        stats.getLocalHeapSize(),
                        cacheConfiguration.getMaxEntriesLocalHeap(),
                        cacheConfiguration.isOverflowToDisk(),
                        cacheConfiguration.isEternal(),
                        cacheConfiguration.getTimeToLiveSeconds(),
                        cacheConfiguration.getTimeToIdleSeconds(),
                        cacheConfiguration.getMemoryStoreEvictionPolicy().toString(),
                        stats.getLocalDiskSize(),
                        stats.getCore().get().value(CacheOperationOutcomes.GetOutcome.HIT),
                        stats.getExtended().allMiss().count().value(),
                        stats.getLocalHeapSizeInBytes(),
                        stats.getLocalDiskSizeInBytes(),
                        nativeCache.isDisabled()
                )
        );

    }
    return rez;
}
 
Example #15
Source File: InMemoryConfiguration.java    From find with MIT License 5 votes vote down vote up
@Bean
public CacheConfiguration defaultCacheConfiguration() {
    return new CacheConfiguration()
            .eternal(false)
            .maxElementsInMemory(1000)
            .overflowToDisk(false)
            .diskPersistent(false)
            .timeToIdleSeconds(0)
            .timeToLiveSeconds(30 * 60)
            .memoryStoreEvictionPolicy(MemoryStoreEvictionPolicy.LRU);
}
 
Example #16
Source File: EHCacheReplayCache.java    From steady with Apache License 2.0 5 votes vote down vote up
public EHCacheReplayCache(String key, Bus b, URL configFileURL) {
    bus = b;
    if (bus != null) {
        bus.getExtension(BusLifeCycleManager.class).registerLifeCycleListener(this);
    }
    cacheManager = EHCacheManagerHolder.getCacheManager(bus, configFileURL);
    
    CacheConfiguration cc = EHCacheManagerHolder.getCacheConfiguration(key, cacheManager);

    Ehcache newCache = new Cache(cc);
    cache = cacheManager.addCacheIfAbsent(newCache);
}
 
Example #17
Source File: EHCacheTokenStore.java    From steady with Apache License 2.0 5 votes vote down vote up
public EHCacheTokenStore(String key, Bus b, URL configFileURL) {
    bus = b;
    if (bus != null) {
        b.getExtension(BusLifeCycleManager.class).registerLifeCycleListener(this);
    }

    cacheManager = EHCacheManagerHolder.getCacheManager(bus, configFileURL);
    // Cannot overflow to disk as SecurityToken Elements can't be serialized
    CacheConfiguration cc = EHCacheManagerHolder.getCacheConfiguration(key, cacheManager);
    cc.overflowToDisk(false); //tokens not writable
    
    Ehcache newCache = new Cache(cc);
    cache = cacheManager.addCacheIfAbsent(newCache);
}
 
Example #18
Source File: DefaultCacheManagerProvider.java    From jerseyoauth2 with MIT License 5 votes vote down vote up
public DefaultCacheManagerProvider()
{
	net.sf.ehcache.config.Configuration config = new net.sf.ehcache.config.Configuration();
	config.setUpdateCheck(false);
	CacheConfiguration tokenCacheConfiguration = new CacheConfiguration().
			maxEntriesLocalHeap(DEFAULT_MAX_CACHE_ENTRIES).
			name("tokenCache").
			persistence(new PersistenceConfiguration().strategy(Strategy.NONE));
	tokenCacheConfiguration.validateConfiguration();
	config.addCache(tokenCacheConfiguration );
	cacheManager = CacheManager.create(config);
}
 
Example #19
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 #20
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 #21
Source File: EhcacheConstructorInterceptor.java    From skywalking with Apache License 2.0 5 votes vote down vote up
@Override
public void onConstruct(EnhancedInstance objInst, Object[] allArguments) {
    CacheConfiguration cacheConfiguration = (CacheConfiguration) allArguments[0];

    // get cache name
    if (cacheConfiguration != null) {
        objInst.setSkyWalkingDynamicField(new EhcacheEnhanceInfo(cacheConfiguration.getName()));
    }
}
 
Example #22
Source File: CacheInitializer.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
/**
 * Configure
 * 
 * @param cacheConfig
 * @return
 */
public CacheInitializer initialize(CacheConfiguration cacheConfig) {
	if (configMap == null) {
		throw new IllegalStateException(
				"You must configure the initializer first.");
	}
	Method[] methods = cacheConfig.getClass().getMethods();
	for (Method method : methods) {
		if (Modifier.isPublic(method.getModifiers())
				&& method.getName().startsWith("set")
				&& method.getParameterTypes().length == 1) {
			// Ok we can handle this method.
			String key = Character.toLowerCase(method.getName().charAt(
					"set".length()))
					+ method.getName().substring("set".length() + 1);
			log.debug("Looking in config map for: {}", key);
			String value = configMap.get(key);
			if (value != null) {
				Class clazz = method.getParameterTypes()[0];
				log.debug("Need to convert to :" + clazz);
				Object obj = covertValue(value, clazz);

				if (obj != null) {
					invokeMethod(method, cacheConfig, obj);
					log.debug("Setting {}#{} to {}", clazz, key, value);
				}

			}

		}
	}
	return this;
}
 
Example #23
Source File: EhcacheMap.java    From concurrentlinkedhashmap with Apache License 2.0 5 votes vote down vote up
public EhcacheMap(MemoryStoreEvictionPolicy evictionPolicy, CacheFactory builder) {
  CacheConfiguration config = new CacheConfiguration(DEFAULT_CACHE_NAME, builder.maximumCapacity);
  config.setMemoryStoreEvictionPolicyFromObject(evictionPolicy);
  CacheManager cacheManager = new CacheManager();
  cache = new Cache(config);
  cache.setCacheManager(cacheManager);
  cache.initialise();
}
 
Example #24
Source File: CacheInitializer.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
/**
 * Configure
 * 
 * @param cacheConfig
 * @return
 */
public CacheInitializer initialize(CacheConfiguration cacheConfig) {
	if (configMap == null) {
		throw new IllegalStateException(
				"You must configure the initializer first.");
	}
	Method[] methods = cacheConfig.getClass().getMethods();
	for (Method method : methods) {
		if (Modifier.isPublic(method.getModifiers())
				&& method.getName().startsWith("set")
				&& method.getParameterTypes().length == 1) {
			// Ok we can handle this method.
			String key = Character.toLowerCase(method.getName().charAt(
					"set".length()))
					+ method.getName().substring("set".length() + 1);
			log.debug("Looking in config map for: {}", key);
			String value = configMap.get(key);
			if (value != null) {
				Class clazz = method.getParameterTypes()[0];
				log.debug("Need to convert to :" + clazz);
				Object obj = covertValue(value, clazz);

				if (obj != null) {
					invokeMethod(method, cacheConfig, obj);
					log.debug("Setting {}#{} to {}", clazz, key, value);
				}

			}

		}
	}
	return this;
}
 
Example #25
Source File: CacheInformationProvider.java    From gocd with Apache License 2.0 5 votes vote down vote up
public Map<String, Object> getCacheConfigurationInformationAsJson(Cache cache) {
    CacheConfiguration config = cache.getCacheConfiguration();
    LinkedHashMap<String, Object> json = new LinkedHashMap<>();

    json.put("Name", config.getName());
    json.put("Maximum Elements in Memory", config.getMaxEntriesLocalHeap());
    json.put("Maximum Elements on Disk", config.getMaxBytesLocalDisk());
    json.put("Memory Store Eviction Policy", config.getMemoryStoreEvictionPolicy().toString());
    json.put("Clean or Flush", config.isClearOnFlush());
    json.put("Eternal", config.isEternal());
    json.put("Time To Idle Seconds", config.getTimeToIdleSeconds());
    json.put("time To Live Seconds", config.getTimeToLiveSeconds());
    if (config.getPersistenceConfiguration() != null) {
        json.put("Persistence Configuration Strategy", config.getPersistenceConfiguration().getStrategy());
        json.put("Persistence Configuration Synchronous writes", config.getPersistenceConfiguration().getSynchronousWrites());
    } else {
        json.put("Persistence Configuration Strategy", "NONE");
        json.put("Persistence Configuration Synchronous writes", false);
    }
    json.put("Disk Spool Buffer Size in MB", config.getDiskSpoolBufferSizeMB());
    json.put("Disk Access Stripes", config.getDiskAccessStripes());
    json.put("Disk Expiry Thread Interval Seconds", config.getDiskExpiryThreadIntervalSeconds());
    json.put("Logging Enabled", config.getLogging());
    json.put("Terracotta Configuration", config.getTerracottaConfiguration());
    json.put("Cache Writer Configuration", config.getCacheWriterConfiguration());
    json.put("Cache Loader Configurations", config.getCacheLoaderConfigurations());
    json.put("Frozen", config.isFrozen());
    json.put("Transactional Mode", config.getTransactionalMode());
    json.put("Statistics Enabled", config.getStatistics());

    return json;
}
 
Example #26
Source File: GoCacheFactory.java    From gocd with Apache License 2.0 5 votes vote down vote up
public GoCacheFactory(TransactionSynchronizationManager transactionSynchronizationManager,
                      @Value("${cruise.cache.elements.limit}") int maxElementsInMemory,
                      @Value("${cruise.cache.is.eternal}") boolean eternal) {
    this.transactionSynchronizationManager = transactionSynchronizationManager;
    cacheConfiguration = new CacheConfiguration("goCache", maxElementsInMemory)
            .persistence(new PersistenceConfiguration().strategy(PersistenceConfiguration.Strategy.NONE))
            .eternal(eternal)
            .memoryStoreEvictionPolicy(MemoryStoreEvictionPolicy.LRU);
}
 
Example #27
Source File: IbisCacheManager.java    From iaf with Apache License 2.0 5 votes vote down vote up
private IbisCacheManager() {
	Configuration cacheManagerConfig = new Configuration();
	String cacheDir = AppConstants.getInstance().getResolvedProperty(CACHE_DIR_KEY);
	if (StringUtils.isNotEmpty(cacheDir)) {
		log.debug("setting cache directory to ["+cacheDir+"]");
		DiskStoreConfiguration diskStoreConfiguration = new DiskStoreConfiguration();
		diskStoreConfiguration.setPath(cacheDir);
		cacheManagerConfig.addDiskStore(diskStoreConfiguration);
	} 
	CacheConfiguration defaultCacheConfig = new CacheConfiguration();
	cacheManagerConfig.addDefaultCache(defaultCacheConfig);
	cacheManager= new CacheManager(cacheManagerConfig);
}
 
Example #28
Source File: DomainAccessControlStoreEhCache.java    From joynr with Apache License 2.0 5 votes vote down vote up
private Cache createAclCache(CacheId cacheId) {
    // configure cache as searchable
    CacheConfiguration cacheConfig = new CacheConfiguration(cacheId.getIdAsString(), 0).eternal(true);
    Searchable searchable = new Searchable();
    cacheConfig.addSearchable(searchable);
    // register searchable attributes
    searchable.addSearchAttribute(new SearchAttribute().name(UserDomainInterfaceOperationKey.USER_ID));
    searchable.addSearchAttribute(new SearchAttribute().name(UserDomainInterfaceOperationKey.DOMAIN));
    searchable.addSearchAttribute(new SearchAttribute().name(UserDomainInterfaceOperationKey.INTERFACE));
    searchable.addSearchAttribute(new SearchAttribute().name(UserDomainInterfaceOperationKey.OPERATION));
    cacheManager.addCache(new Cache(cacheConfig));
    return cacheManager.getCache(cacheId.getIdAsString());
}
 
Example #29
Source File: DomainAccessControlStoreEhCache.java    From joynr with Apache License 2.0 5 votes vote down vote up
private Cache createDrtCache() {
    // configure cache as searchable
    CacheConfiguration cacheConfig = new CacheConfiguration(CacheId.DOMAIN_ROLES.getIdAsString(), 0).eternal(true);
    Searchable searchable = new Searchable();
    cacheConfig.addSearchable(searchable);
    // register searchable attributes
    searchable.addSearchAttribute(new SearchAttribute().name(UserRoleKey.USER_ID));
    searchable.addSearchAttribute(new SearchAttribute().name(UserRoleKey.ROLE));
    cacheManager.addCache(new Cache(cacheConfig));
    return cacheManager.getCache(CacheId.DOMAIN_ROLES.getIdAsString());
}
 
Example #30
Source File: EhCacheCacheManagerTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Before
public void setup() {
	nativeCacheManager = new CacheManager(new Configuration().name("EhCacheCacheManagerTests")
			.defaultCache(new CacheConfiguration("default", 100)));
	addNativeCache(CACHE_NAME);

	cacheManager = new EhCacheCacheManager(nativeCacheManager);
	cacheManager.setTransactionAware(false);
	cacheManager.afterPropertiesSet();

	transactionalCacheManager = new EhCacheCacheManager(nativeCacheManager);
	transactionalCacheManager.setTransactionAware(true);
	transactionalCacheManager.afterPropertiesSet();
}