/** * http://www.ehcache.org/documentation/2.8/code-samples.html#creating-caches-programmatically */ EhCacheWrapper(String cacheName) { AppConfiguration.Cache config = AppConfiguration.CONFIG.getCache(); // Create a Cache specifying its configuration cache = new Cache( new CacheConfiguration(cacheName, config.getMaxSize()) .timeToLiveSeconds(TimeUnit.MINUTES.toSeconds(config.getLifeTime())) .eternal(false) .persistence(new PersistenceConfiguration().strategy(Strategy.NONE)) .memoryStoreEvictionPolicy(MemoryStoreEvictionPolicy.FIFO) ); // The cache is not usable until it has been added manager.addCache(cache); }
@Override public void init(ComponentRepository repo, LinkedHashMap<String, String> configuration) throws Exception { NonVersionedRedisSecuritySource source = new NonVersionedRedisSecuritySource(getRedisConnector().getJedisPool(), getRedisPrefix()); SecuritySource rawSource = source; if ((getCacheManager() != null) && (getLruCacheElements() > 0)) { Cache cache = new Cache("NonVersionedRedisSecuritySource", getLruCacheElements(), MemoryStoreEvictionPolicy.LRU, false, null, true, -1L, -1L, false, -1L, null); getCacheManager().addCache(cache); rawSource = new NonVersionedEHCachingSecuritySource(source, cache); } String rawClassifier = getCachingClassifier() != null ? getCachingClassifier() : getClassifier(); ComponentInfo sourceInfo = new ComponentInfo(SecuritySource.class, rawClassifier); sourceInfo.addAttribute(ComponentInfoAttributes.LEVEL, 1); sourceInfo.addAttribute(ComponentInfoAttributes.REMOTE_CLIENT_JAVA, RemoteSecuritySource.class); repo.registerComponent(sourceInfo, rawSource); ComponentInfo redisInfo = new ComponentInfo(NonVersionedRedisSecuritySource.class, getClassifier()); redisInfo.addAttribute(ComponentInfoAttributes.LEVEL, 1); repo.registerComponent(redisInfo, source); if (isPublishRest()) { repo.getRestComponents().publish(sourceInfo, new DataSecuritySourceResource(rawSource)); } }
public void setCacheValue(String cacheName, String keyName, Collection<Attribute> attrs, int tti, int ttl) { CacheManager manager = Context.getInstance().getCacheManager(); Cache cache = manager.getCache(cacheName); if (cache == null) { cache = new Cache( new CacheConfiguration(cacheName, 1000) .memoryStoreEvictionPolicy(MemoryStoreEvictionPolicy.LRU) .eternal(false) .timeToLiveSeconds(60) .timeToIdleSeconds(60) .diskExpiryThreadIntervalSeconds(120) .persistence(new PersistenceConfiguration().strategy(Strategy.LOCALTEMPSWAP))); manager.addCache(cache); } cache.put(new net.sf.ehcache.Element(keyName, attrs, false, tti, ttl)); }
private Cache getOrCreateCache() { // Create a singleton CacheManager using defaults CacheManager manager = CacheManager.create(); // Create a Cache specifying its configuration Cache c = manager.getCache(CACHE_name); if (c == null) { c = new Cache(new CacheConfiguration(CACHE_name, CACHE_maxEntriesLocalHeap) .memoryStoreEvictionPolicy(MemoryStoreEvictionPolicy.LFU) .eternal(true) .persistence( new PersistenceConfiguration() .strategy(Strategy.LOCALTEMPSWAP))); manager.addCache(c); } return c; }
/** * Inits the cache ehcache big memory. */ @SuppressWarnings("deprecation") private static void initCacheEhcacheBigMemory() { // Create a CacheManager using defaults sEhcacheManager = CacheManager.create(); // Create a Cache specifying its configuration. sEhcacheCache = new Cache(new CacheConfiguration("test", 10000) .memoryStoreEvictionPolicy(MemoryStoreEvictionPolicy.LRU) .overflowToDisk(false).eternal(false).timeToLiveSeconds(6000) .timeToIdleSeconds(6000).diskPersistent(false) .diskExpiryThreadIntervalSeconds(0).overflowToOffHeap(true) .maxMemoryOffHeap(sBigMemorySize)); sEhcacheManager.addCache(sEhcacheCache); }
/** * Inits the cache ehcache. */ @SuppressWarnings("deprecation") private static void initCacheEhcache() { // Create a CacheManager using defaults sEhcacheManager = CacheManager.create(); // Create a Cache specifying its configuration. sEhcacheCache = new Cache(new CacheConfiguration("test", (int) sCacheItemsLimit).memoryStoreEvictionPolicy( MemoryStoreEvictionPolicy.LRU).overflowToDisk(false).eternal( false).timeToLiveSeconds(6000).timeToIdleSeconds(6000) .diskPersistent(false).diskExpiryThreadIntervalSeconds(0)); sEhcacheManager.addCache(sEhcacheCache); }
public LocalCacheManager(String name, int max, int exptime, boolean copyOnRead, boolean copyOnWrite) { this.cache = CacheManager.getInstance().getCache(name); if (cache == null) { CacheConfiguration config = new CacheConfiguration(name, max) .copyOnRead(copyOnRead) .copyOnWrite(copyOnWrite) .memoryStoreEvictionPolicy(MemoryStoreEvictionPolicy.LRU) .eternal(false) .timeToLiveSeconds(exptime) .timeToIdleSeconds(exptime) .diskExpiryThreadIntervalSeconds(60) .persistence(new PersistenceConfiguration().strategy(PersistenceConfiguration.Strategy.NONE)); this.cache = new Cache(config, null, null); CacheManager.getInstance().addCache(cache); if (logger.isInfoEnabled()) { logger.info("Arcus k/v local cache is enabled : %s", cache.toString()); } } }
public void open() { Cache configCache = new Cache( getName(), getMaxElementsInMemory(), MemoryStoreEvictionPolicy.fromString(getMemoryStoreEvictionPolicy()), isOverflowToDisk(), null, isEternal(), getTimeToLiveSeconds(), getTimeToIdleSeconds(), isDiskPersistent(), getDiskExpiryThreadIntervalSeconds(), null, null, getMaxElementsOnDisk() ); cacheManager=IbisCacheManager.getInstance(); cache = cacheManager.addCache(configCache); }
protected CacheConfiguration createCacheConfiguration(int _maxElements) { MemoryStoreEvictionPolicy _policy = MemoryStoreEvictionPolicy.LRU; switch (algorithm) { case CLOCK: _policy = MemoryStoreEvictionPolicy.CLOCK; break; } CacheConfiguration c = new CacheConfiguration(CACHE_NAME, _maxElements) .memoryStoreEvictionPolicy(_policy) .eternal(true) .diskExpiryThreadIntervalSeconds(0) .persistence(new PersistenceConfiguration().strategy(PersistenceConfiguration.Strategy.NONE)); if (withExpiry) { c.setEternal(false); c.setTimeToLiveSeconds(5 * 60); } return c; }
public RealCache() { super(); CacheManager manager = null; synchronized (RealCache.class) { manager = CacheManager.getInstance(); if (!manager.cacheExists("AFPDataGrabberCache")) { Cache cache = new Cache(new CacheConfiguration("AFPDataGrabberCache", 50000).memoryStoreEvictionPolicy(MemoryStoreEvictionPolicy.LFU) .eternal(true).timeToLiveSeconds(0).timeToIdleSeconds(0).persistence(new PersistenceConfiguration().strategy(Strategy.NONE))); manager.addCache(cache); } } ehcache = manager.getCache("AFPDataGrabberCache"); }
@SuppressWarnings("deprecation") @Override public void afterPropertiesSet() throws Exception { Cache.ID = key + "." + Dates.newDateStringOfFormatDateTimeSSSNoneSpace(); Cache.HOST = Utils.getLocalHostIP(); Cache.CACHE_STORE = key + spliter + "cache" + spliter + "store"; Cache.CACHE_STORE_SYNC = Cache.CACHE_STORE + spliter + "sync"; if (this.localEnabled) { Configuration configuration = new Configuration(); configuration.setName(Cache.ID); configuration.setMaxBytesLocalHeap(localMaxBytesLocalHeap); configuration.setMaxBytesLocalDisk(localMaxBytesLocalDisk); // DiskStore // 每次启动设置新的文件地址,以避免重启期间一级缓存未同步,以及单机多应用启动造成EhcacheManager重复的问题. DiskStoreConfiguration dsc = new DiskStoreConfiguration(); dsc.setPath(localStoreLocation + Cache.ID); configuration.diskStore(dsc); // DefaultCache CacheConfiguration defaultCacheConfiguration = new CacheConfiguration(); defaultCacheConfiguration.setEternal(false); defaultCacheConfiguration.setOverflowToDisk(true); defaultCacheConfiguration.setDiskPersistent(false); defaultCacheConfiguration.memoryStoreEvictionPolicy(MemoryStoreEvictionPolicy.LRU); defaultCacheConfiguration.setDiskExpiryThreadIntervalSeconds(localDiskExpiryThreadIntervalSeconds); // 默认false,使用引用.设置为true,避免外部代码修改了缓存对象.造成EhCache的缓存对象也随之改变 // 但是设置为true后,将引起element的tti不自动刷新.如果直接新建element去覆盖原值.则本地ttl和远程ttl会产生一定的误差. // 因此,使用时放弃手动覆盖方式刷新本地tti,当本地tti过期后,自动从Redis中再获取即可. defaultCacheConfiguration.copyOnRead(true); defaultCacheConfiguration.copyOnWrite(true); defaultCacheConfiguration.setTimeToIdleSeconds(localTimeToIdleSeconds); defaultCacheConfiguration.setTimeToLiveSeconds(localTimeToLiveSeconds); configuration.setDefaultCacheConfiguration(defaultCacheConfiguration); configuration.setDynamicConfig(false); configuration.setUpdateCheck(false); this.cacheManager = new CacheManager(configuration); this.cacheSync = new RedisPubSubSync(this);// 使用Redis Topic发送订阅缓存变更消息 } }
static Cache createLifeCache(CacheManager manager, String name) { return createCache( manager, name, configuration -> configuration.memoryStoreEvictionPolicy(MemoryStoreEvictionPolicy.FIFO) .timeToLiveSeconds(LIFE_TIME_SEC)); }
static Cache createIdleCache(CacheManager manager, String name) { return createCache( manager, name, configuration -> configuration.memoryStoreEvictionPolicy(MemoryStoreEvictionPolicy.FIFO) .timeToIdleSeconds(IDLE_TIME_SEC)); }
static Cache createEternalCache(CacheManager manager, String name) { return createCache( manager, name, configuration -> configuration.memoryStoreEvictionPolicy(MemoryStoreEvictionPolicy.FIFO) .eternal(true)); }
static Cache createLifeCache(CacheManager manager, String name) { CacheConfiguration configuration = new CacheConfiguration(name, MAX_ENTRIES); configuration.memoryStoreEvictionPolicy(MemoryStoreEvictionPolicy.FIFO) .timeToLiveSeconds(LIFE_TIME_SEC); Cache cache = new Cache(configuration); manager.addCache(cache); return cache; }
static Cache createIdleCache(CacheManager manager, String name) { CacheConfiguration configuration = new CacheConfiguration(name, MAX_ENTRIES); configuration.memoryStoreEvictionPolicy(MemoryStoreEvictionPolicy.FIFO) .timeToIdleSeconds(IDLE_TIME_SEC); Cache cache = new Cache(configuration); manager.addCache(cache); return cache; }
static Cache createEternalCache(CacheManager manager, String name) { CacheConfiguration configuration = new CacheConfiguration(name, MAX_ENTRIES); configuration.memoryStoreEvictionPolicy(MemoryStoreEvictionPolicy.FIFO) .eternal(true); Cache cache = new Cache(configuration); manager.addCache(cache); return cache; }
@Converter public static MemoryStoreEvictionPolicy toPolicy(String s) { if (s == null) { return null; } s = s.replace("MemoryStoreEvictionPolicy.", ""); return MemoryStoreEvictionPolicy.fromString(s); }
@BeforeClass public static void setUpGlobal() { final Configuration config = new Configuration(); config.addDefaultCache( new CacheConfiguration("default", Integer.MAX_VALUE) .memoryStoreEvictionPolicy(MemoryStoreEvictionPolicy.LFU) .overflowToDisk(false)); CACHE_MANAGER = CacheManager.create(config); }
@Bean public CacheConfiguration defaultCacheConfiguration() { return new CacheConfiguration() .eternal(false) .maxElementsInMemory(1000) .overflowToDisk(false) .diskPersistent(false) .timeToIdleSeconds(0) .timeToLiveSeconds(30 * 60) .memoryStoreEvictionPolicy(MemoryStoreEvictionPolicy.LRU); }
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(); }
@Test public void memoryStoreEvictionPolicy() { Config config = ConfigFactory .empty() .withValue("memoryStoreEvictionPolicy", fromAnyRef("LRU")); CacheConfigurationBuilder builder = new CacheConfigurationBuilder("c1"); CacheConfiguration cache = builder.build(config); assertEquals(MemoryStoreEvictionPolicy.LRU, cache.getMemoryStoreEvictionPolicy()); }
public EhCacheMemory() { DiskStoreConfiguration diskStoreConfiguration = new DiskStoreConfiguration(); diskStoreConfiguration.setPath("/tmp"); Configuration configuration = new Configuration(); configuration.addDiskStore(diskStoreConfiguration); CacheConfiguration cacheConf = new CacheConfiguration("cache_memory", Integer.MAX_VALUE).memoryStoreEvictionPolicy(MemoryStoreEvictionPolicy.LRU).overflowToDisk(false).eternal(false).diskExpiryThreadIntervalSeconds(0); CacheManager cacheManager = new CacheManager(configuration); cacheManager.addCache(new Cache(cacheConf)); cache = cacheManager.getEhcache("cache_memory"); }
public EhCacheDisk() { DiskStoreConfiguration diskStoreConfiguration = new DiskStoreConfiguration(); diskStoreConfiguration.setPath("/tmp"); Configuration configuration = new Configuration(); configuration.addDiskStore(diskStoreConfiguration); CacheConfiguration cacheConf = new CacheConfiguration("cache_disk", 0).memoryStoreEvictionPolicy(MemoryStoreEvictionPolicy.LRU).overflowToDisk(false).eternal(false).diskExpiryThreadIntervalSeconds(0); CacheManager cacheManager = new CacheManager(configuration); cacheManager.addCache(new Cache(cacheConf)); cache = cacheManager.getEhcache("cache_disk"); }
public Cache createCache() throws IOException { factoryBean.setCacheManager(createCacheManager()); factoryBean.setCacheName("userCache"); factoryBean.setDiskPersistent(false); factoryBean.setOverflowToDisk(false); factoryBean.setMaxElementsInMemory(1000); factoryBean.setEternal(true); factoryBean.setMemoryStoreEvictionPolicy(MemoryStoreEvictionPolicy.LRU); factoryBean.afterPropertiesSet(); return (Cache) factoryBean.getObject(); }
public TimeBasedSizeBoundReportableEntityStore(String name, int timeToIdleInSeconds, int timeToLiveInSeconds, int size) { super(name, timeToIdleInSeconds, timeToLiveInSeconds); getEhCacheFactoryBean().setMemoryStoreEvictionPolicy(MemoryStoreEvictionPolicy.FIFO); getEhCacheFactoryBean().setMaxElementsInMemory(size); initEhCache(); }
private void createCache(AppConstants ac) { if (isDiskPersistent() && !isOverflowToDisk()) { log.info("setting overflowToDisk true, to support diskPersistent=true"); setOverflowToDisk(true); } String DiskStorePath = null; String cacheDir = ac.getResolvedProperty("etag.ehcache.dir"); if (StringUtils.isNotEmpty(cacheDir)) { DiskStorePath = cacheDir; } Cache configCache = new Cache( KEY_CACHE_NAME, maxElementsInMemory, MemoryStoreEvictionPolicy.fromString(memoryStoreEvictionPolicy), isOverflowToDisk(), DiskStorePath, isEternal(), 0, 0, isDiskPersistent(), diskExpiryThreadIntervalSeconds, null, null, getMaxElementsOnDisk() ); cache = cacheManager.addCache(configCache); }
public void configure(String ownerName) throws ConfigurationException { super.configure(ownerName); if (isDiskPersistent() && !isOverflowToDisk()) { log.info("setting overflowToDisk true, to support diskPersistent=true"); setOverflowToDisk(true); } MemoryStoreEvictionPolicy.fromString(getMemoryStoreEvictionPolicy()); }
public void setMemoryStoreEvictionPolicy( MemoryStoreEvictionPolicy memoryStoreEvictionPolicy) { this.memoryStoreEvictionPolicy = memoryStoreEvictionPolicy; }
public MemoryStoreEvictionPolicy getMemoryStoreEvictionPolicy() { return memoryStoreEvictionPolicy; }
@Test public void basicTest() throws InterruptedException { System.out.println("runtime used memory: " + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / 1024 / 1024 + "M"); Configuration conf = new Configuration(); conf.setMaxBytesLocalHeap("100M"); CacheManager cacheManager = CacheManager.create(conf); //Create a Cache specifying its configuration. Cache testCache = //Create a Cache specifying its configuration. new Cache(new CacheConfiguration("test", 0).// memoryStoreEvictionPolicy(MemoryStoreEvictionPolicy.LRU).// eternal(false).// timeToIdleSeconds(86400).// diskExpiryThreadIntervalSeconds(0).// //maxBytesLocalHeap(1000, MemoryUnit.MEGABYTES).// persistence(new PersistenceConfiguration().strategy(PersistenceConfiguration.Strategy.NONE))); cacheManager.addCache(testCache); System.out.println("runtime used memory: " + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / 1024 / 1024 + "M"); byte[] blob = new byte[(1024 * 80 * 1024)];//400M Random random = new Random(); for (int i = 0; i < blob.length; i++) { blob[i] = (byte) random.nextInt(); } // List<String> manyObjects = Lists.newArrayList(); // for (int i = 0; i < 10000; i++) { // manyObjects.add(new String("" + i)); // } // testCache.put(new Element("0", manyObjects)); testCache.put(new Element("1", blob)); System.out.println(testCache.get("1") == null); System.out.println(testCache.getSize()); System.out.println(testCache.getStatistics().getLocalHeapSizeInBytes()); System.out.println("runtime used memory: " + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / 1024 / 1024 + "M"); blob = new byte[(1024 * 80 * 1024)];//400M for (int i = 0; i < blob.length; i++) { blob[i] = (byte) random.nextInt(); } testCache.put(new Element("2", blob)); System.out.println(testCache.get("1") == null); System.out.println(testCache.get("2") == null); System.out.println(testCache.getSize()); System.out.println(testCache.getStatistics().getLocalHeapSizeInBytes()); System.out.println("runtime used memory: " + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / 1024 / 1024 + "M"); blob = new byte[(1024 * 80 * 1024)];//400M for (int i = 0; i < blob.length; i++) { blob[i] = (byte) random.nextInt(); } testCache.put(new Element("3", blob)); System.out.println(testCache.get("1") == null); System.out.println(testCache.get("2") == null); System.out.println(testCache.get("3") == null); System.out.println(testCache.getSize()); System.out.println(testCache.getStatistics().getLocalHeapSizeInBytes()); System.out.println("runtime used memory: " + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / 1024 / 1024 + "M"); cacheManager.shutdown(); }
public void setMemoryStoreEvictionPolicy(MemoryStoreEvictionPolicy memoryStoreEvictionPolicy) { factoryBean.setMemoryStoreEvictionPolicy(memoryStoreEvictionPolicy); }
@PostConstruct @SuppressWarnings("unused") private void init() throws Exception { // Init Cache Configuration c = new Configuration(); c.setName("sessionManager"); manager = CacheManager.create(c); CacheConfiguration config = new CacheConfiguration(); config.eternal(false).name(CACHE_NAME).maxEntriesLocalHeap(maxEntries).memoryStoreEvictionPolicy(MemoryStoreEvictionPolicy.LRU).timeToIdleSeconds(timeToIdle).timeToLiveSeconds(timeToLive); if (!manager.cacheExists(CACHE_NAME)) { manager.addCache(new Cache(config)); } sessions = manager.getCache(CACHE_NAME); // Init JMS replication ConnectionFactory factory = new ActiveMQConnectionFactory(this.url); Connection conn = factory.createConnection(); conn.start(); jmsSession = (TopicSession) conn.createSession(false, Session.AUTO_ACKNOWLEDGE); final Topic topic = jmsSession.createTopic(TOPIC_NAME); tp = jmsSession.createPublisher(topic); listener = new Thread() { // Thread created once upon container startup @Override public void run() { try { MessageConsumer consumer = jmsSession.createConsumer(topic); while (live) { ObjectMessage msg = (ObjectMessage) consumer.receive(); LOG.debug("Received replication message: {}", msg); if (PUT.equals(msg.getStringProperty(ACTION_KEY))) { sessions.put(new Element(msg.getStringProperty(TOKEN_KEY), msg.getObject())); } else if (REMOVE.equals(msg.getStringProperty(ACTION_KEY))) { sessions.remove(msg.getStringProperty(TOKEN_KEY)); } } } catch (JMSException e) { LOG.error("Error reading replication message", e); } } }; listener.start(); }
private static Cache getCache() { if(cache == null) { System.setProperty("net.sf.ehcache.skipUpdateCheck", "true"); CacheManager manager = CacheManager.create(); //Create a Cache specifying its configuration. cache = new Cache( new CacheConfiguration(vImage.class.getSimpleName(), 500) .memoryStoreEvictionPolicy(MemoryStoreEvictionPolicy.LFU) .eternal(false) .timeToLiveSeconds(60 * 60) .timeToIdleSeconds(60 * 60) ); MetricsFactory.getMetricRegistry().register(MetricRegistry.name(vImage.class.getSimpleName(), "images", "cache", "count"), (Gauge<Integer>) () -> cache.getSize()); manager.addCache(cache); } cache.evictExpiredElements(); return cache; }