/** * Predict the particular {@code Ehcache} implementation that will be returned from * {@link #getObject()} based on logic in {@link #createCache()} and * {@link #decorateCache(Ehcache)} as orchestrated by {@link #afterPropertiesSet()}. */ @Override public Class<? extends Ehcache> getObjectType() { if (this.cache != null) { return this.cache.getClass(); } if (this.cacheEntryFactory != null) { if (this.cacheEntryFactory instanceof UpdatingCacheEntryFactory) { return UpdatingSelfPopulatingCache.class; } else { return SelfPopulatingCache.class; } } if (this.blocking) { return BlockingCache.class; } return Cache.class; }
@SuppressWarnings("unchecked") @Override public Collection<Session> getAllSessions() { Collection<Session> sessions = new ArrayList<Session>(0); try { Object object = cacheManager.getCache(this.activeSessionsCacheName).getNativeCache(); if(object instanceof Ehcache) { Ehcache ehcache = (Ehcache)object; List<Serializable> keys = ehcache.getKeysWithExpiryCheck(); if (!CollectionUtils.isEmpty(keys)) { for (Serializable key : keys) { sessions.add(getSession(key)); } } } } catch (Exception e) { logger.error("获取全部session异常", e); } return sessions; }
/** * Use the Ehcache provided search API to perform criteria queries on defined search attributes. * NOTE: Requires search attributes to be previously defined in Ehcache config! * DEPRECATED because at observed large cache quantities the search noticeably slows down the system * @param params the search parameters as key/value pairs * @return the first found cache hit */ @Deprecated @SuppressWarnings("unchecked") public VALUE lookup(Map<String, String> params) { Query q = cache.createQuery(); for (Map.Entry<String, String> param : params.entrySet()) { Attribute<String> theAttribute = ((Ehcache) cache).getSearchAttribute(param.getKey()); q.addCriteria(theAttribute.eq(param.getValue())); } q.includeKeys().includeValues(); Results results = q.execute(); if (results == null || results.size() == 0) { return null; } if (results.size() > 1) { log.warn("There are multiple entries registered for params: {}", params.toString()); } return (VALUE) results.all().get(0).getValue(); }
@Test public void testEhCacheFactoryBeanWithBlockingCache() throws Exception { EhCacheManagerFactoryBean cacheManagerFb = new EhCacheManagerFactoryBean(); cacheManagerFb.afterPropertiesSet(); try { CacheManager cm = cacheManagerFb.getObject(); EhCacheFactoryBean cacheFb = new EhCacheFactoryBean(); cacheFb.setCacheManager(cm); cacheFb.setCacheName("myCache1"); cacheFb.setBlocking(true); assertEquals(cacheFb.getObjectType(), BlockingCache.class); cacheFb.afterPropertiesSet(); Ehcache myCache1 = cm.getEhcache("myCache1"); assertTrue(myCache1 instanceof BlockingCache); } finally { cacheManagerFb.destroy(); } }
@Test public void testEhCacheFactoryBeanWithSelfPopulatingCache() throws Exception { EhCacheManagerFactoryBean cacheManagerFb = new EhCacheManagerFactoryBean(); cacheManagerFb.afterPropertiesSet(); try { CacheManager cm = cacheManagerFb.getObject(); EhCacheFactoryBean cacheFb = new EhCacheFactoryBean(); cacheFb.setCacheManager(cm); cacheFb.setCacheName("myCache1"); cacheFb.setCacheEntryFactory(new CacheEntryFactory() { @Override public Object createEntry(Object key) throws Exception { return key; } }); assertEquals(cacheFb.getObjectType(), SelfPopulatingCache.class); cacheFb.afterPropertiesSet(); Ehcache myCache1 = cm.getEhcache("myCache1"); assertTrue(myCache1 instanceof SelfPopulatingCache); assertEquals("myKey1", myCache1.get("myKey1").getValue()); } finally { cacheManagerFb.destroy(); } }
public long viewHits(Long id) { Ehcache cache = cacheManager.getEhcache(Article.HITS_CACHE_NAME); Element element = cache.get(id); Long hits; if (element != null) { hits = (Long) element.getObjectValue(); } else { Article article = articleDao.find(id); if (article == null) { return 0L; } hits = article.getHits(); } hits++; cache.put(new Element(id, hits)); long time = System.currentTimeMillis(); if (time > viewHitsTime + Article.HITS_CACHE_INTERVAL) { viewHitsTime = time; updateHits(); cache.removeAll(); } return hits; }
public long viewHits(Long id) { Ehcache cache = cacheManager.getEhcache(Product.HITS_CACHE_NAME); Element element = cache.get(id); Long hits; if (element != null) { hits = (Long) element.getObjectValue(); } else { Product product = productDao.find(id); if (product == null) { return 0L; } hits = product.getHits(); } hits++; cache.put(new Element(id, hits)); long time = System.currentTimeMillis(); if (time > viewHitsTime + Product.HITS_CACHE_INTERVAL) { viewHitsTime = time; updateHits(); cache.removeAll(); } return hits; }
public boolean isValid(CacheManager cacheManager, String cacheName, String key) { LOG.trace("Cache Name: {}", cacheName); if (!cacheManager.cacheExists(cacheName)) { LOG.debug("No existing Cache found with name: {}" + ". Please ensure a cache is first instantiated using a Cache Consumer or Cache Producer." + " Replacement will not be performed since the cache {} does not presently exist", cacheName, cacheName); return false; } LOG.debug("Found an existing cache: {}", cacheName); if (LOG.isTraceEnabled()) { LOG.trace("Cache {} currently contains {} elements", cacheName, cacheManager.getCache(cacheName).getSize()); } Ehcache cache = cacheManager.getCache(cacheName); if (!cache.isKeyInCache(key)) { LOG.debug("No Key with name: {} presently exists in the cache. It is also possible that the key may have expired in the cache." + " Replacement will not be performed until an appropriate key/value pair is added to (or) found in the cache.", key); return false; } return true; }
private void dispatchExchange(Ehcache cache, Element element, String operation) { Exchange exchange; LOG.debug("Consumer Dispatching the Exchange containing the Element {} in cache {}", element, cache.getName()); if (element == null) { exchange = cacheConsumer.getEndpoint().createCacheExchange(operation, "", ""); } else { exchange = cacheConsumer.getEndpoint().createCacheExchange(operation, (String) element.getObjectKey(), element.getObjectValue()); } try { cacheConsumer.getProcessor().process(exchange); } catch (Exception e) { throw new CacheException("Error in consumer while dispatching exchange containing key " + (element != null ? element.getObjectKey() : null) + " for further processing", e); } }
@Override public int size() { if (springCache.getNativeCache() instanceof Ehcache) { Ehcache ehcache = (Ehcache) springCache.getNativeCache(); return ehcache.getSize(); } throw new UnsupportedOperationException( "invoke spring cache abstract size method not supported"); }
@Override public Set keys() { if (springCache.getNativeCache() instanceof Ehcache) { Ehcache ehcache = (Ehcache) springCache.getNativeCache(); return new HashSet(ehcache.getKeys()); } throw new UnsupportedOperationException( "invoke spring cache abstract keys method not supported"); }
/** * 创建本地缓存 */ private Ehcache getEhcache(final String name) { Future<Ehcache> future = this.ehcaches.get(name); if (future == null) { Callable<Ehcache> callable = new Callable<Ehcache>() { @Override public Ehcache call() throws Exception { Ehcache cache = cacheManager.getEhcache(name); if (cache == null) { cacheManager.addCache(name); cache = cacheManager.getEhcache(name); } return cache; } }; FutureTask<Ehcache> task = new FutureTask<>(callable); future = this.ehcaches.putIfAbsent(name, task); if (future == null) { future = task; task.run(); } } try { return future.get(); } catch (Exception e) { this.ehcaches.remove(name); throw new CacheException(e); } }
@Override public int size() { if(springCache.getNativeCache() instanceof Ehcache) { Ehcache ehcache = (Ehcache) springCache.getNativeCache(); return ehcache.getSize(); } throw new UnsupportedOperationException("invoke spring cache abstract size method not supported"); }
@Override public Set keys() { if(springCache.getNativeCache() instanceof Ehcache) { Ehcache ehcache = (Ehcache) springCache.getNativeCache(); return new HashSet(ehcache.getKeys()); } throw new UnsupportedOperationException("invoke spring cache abstract keys method not supported"); }
protected void onSetUpInTransaction() { // make a cache CacheManager cacheManager = CacheManager.create(); if (! cacheManager.cacheExists("ehcache.sakai.kaltura.entries")) { cacheManager.addCache("ehcache.sakai.kaltura.entries"); } Ehcache entriesCache = cacheManager.getCache("ehcache.sakai.kaltura.entries"); // create and setup the object to be tested external = new ExternalLogicStub(); service = new KalturaAPIService(); service.setExternal(external); service.setEntriesCache(entriesCache); service.setOffline(true); // for testing we do not try to fetch real data // run the init external.currentUserId = FakeDataPreload.ADMIN_USER_ID; // DEFAULT ADMIN // UNICON settings for testing external.config.put("kaltura.partnerid", 166762); external.config.put("kaltura.adminsecret", "26d08a0ba54c911492bbc7599028295f"); external.config.put("kaltura.secret", "6e4755b613a38b19e4cfb5d7405ed170"); service.testWSInit(); // SPECIAL INIT service.getKalturaClient(); }
public KalturaAPIServiceStub(ExternalLogicStub external, Ehcache entriesCache, Ehcache categoriesCache) { this.external = external; setExternal(external); setEntriesCache(entriesCache); setCategoriesCache(categoriesCache); init(); }
@Override protected void setUp() throws Exception { // THIS IS EXECUTED BEFORE EACH TEST // make the caches CacheManager cacheManager = CacheManager.create(); if (! cacheManager.cacheExists("ehcache.sakai.kaltura.entries")) { cacheManager.addCache("ehcache.sakai.kaltura.entries"); } Ehcache entriesCache = cacheManager.getCache("ehcache.sakai.kaltura.entries"); if (! cacheManager.cacheExists("ehcache.sakai.kaltura.cats")) { cacheManager.addCache("ehcache.sakai.kaltura.cats"); } Ehcache categoriesCache = cacheManager.getCache("ehcache.sakai.kaltura.cats"); // create and setup the object to be tested external = new ExternalLogicStub(); kalturaAPIService = new KalturaAPIServiceStub(external, entriesCache, categoriesCache); kalturaAPIService.setKalturaClippingEnabled(true); // for testing service = new MediaService(); service.setExternal(external); service.setKalturaAPIService(kalturaAPIService); service.setEntriesCache(entriesCache); service.setForceMediaNameOrdering(false); // run the init service.init(); }
/** * Decorate the given Cache, if necessary. * @param cache the raw Cache object, based on the configuration of this FactoryBean * @return the (potentially decorated) cache object to be registered with the CacheManager */ protected Ehcache decorateCache(Ehcache cache) { if (this.cacheEntryFactory != null) { if (this.cacheEntryFactory instanceof UpdatingCacheEntryFactory) { return new UpdatingSelfPopulatingCache(cache, (UpdatingCacheEntryFactory) this.cacheEntryFactory); } else { return new SelfPopulatingCache(cache, this.cacheEntryFactory); } } if (this.blocking) { return new BlockingCache(cache); } return cache; }
@Override public Cache getCache(String name) { Cache cache = super.getCache(name); if (cache == null) { // Check the EhCache cache again (in case the cache was added at runtime) Ehcache ehcache = getCacheManager().getEhcache(name); if (ehcache != null) { addCache(new EhCacheCache(ehcache)); cache = super.getCache(name); // potentially decorated } } return cache; }
/** * Create an {@link EhCacheCache} instance. * @param ehcache backing Ehcache instance */ public EhCacheCache(Ehcache ehcache) { Assert.notNull(ehcache, "Ehcache must not be null"); Status status = ehcache.getStatus(); Assert.isTrue(Status.STATUS_ALIVE.equals(status), "An 'alive' Ehcache is required - current cache is " + status.toString()); this.cache = ehcache; }
public int size() { if(cache.getNativeCache() instanceof Ehcache) { Ehcache ehcache = (Ehcache) cache.getNativeCache(); return ehcache.getSize(); } throw new UnsupportedOperationException("invoke spring cache abstract size method not supported"); }
@SuppressWarnings("unchecked") public Set<K> keys() { if(cache.getNativeCache() instanceof Ehcache) { Ehcache ehcache = (Ehcache) cache.getNativeCache(); return new HashSet<K>(ehcache.getKeys()); } throw new UnsupportedOperationException("invoke spring cache abstract keys method not supported"); }
@Bean public Ehcache ehcache(){ EhCacheFactoryBean cacheFactoryBean = new EhCacheFactoryBean(); cacheFactoryBean.setCacheManager(cacheManager()); cacheFactoryBean.setCacheName("aclCache"); cacheFactoryBean.setMaxBytesLocalHeap("1M"); cacheFactoryBean.setMaxEntriesLocalHeap(0L); cacheFactoryBean.afterPropertiesSet(); return cacheFactoryBean.getObject(); }
@Override @Transactional public void load(Ehcache ehcache) throws CacheException { int i = 1, total = 12; log.info("Caching KML {}/{}...", i++, total); ehcache.put(new Element(new SimpleKey("track", false, false), kmlService.getAllStagesKml("track", false, false), true)); log.info("Caching KML {}/{}...", i++, total); ehcache.put(new Element(new SimpleKey("track", false, true), kmlService.getAllStagesKml("track", false, true), true)); log.info("Caching KML {}/{}...", i++, total); ehcache.put(new Element(new SimpleKey("track", true, false), kmlService.getAllStagesKml("track", true, true), true)); log.info("Caching KML {}/{}...", i++, total); ehcache.put(new Element(new SimpleKey("track", true, true), kmlService.getAllStagesKml("track", true, true), true)); log.info("Caching KML {}/{}...", i++, total); ehcache.put(new Element(new SimpleKey("marcadores", false, false), kmlService.getAllStagesKml("marcadores", false, false), true)); log.info("Caching KML {}/{}...", i++, total); ehcache.put(new Element(new SimpleKey("marcadores", false, true), kmlService.getAllStagesKml("marcadores", false, true), true)); log.info("Caching KML {}/{}...", i++, total); ehcache.put(new Element(new SimpleKey("marcadores", true, false), kmlService.getAllStagesKml("marcadores", true, false), true)); log.info("Caching KML {}/{}...", i++, total); ehcache.put(new Element(new SimpleKey("marcadores", true, true), kmlService.getAllStagesKml("marcadores", true, true), true)); log.info("Caching KML {}/{}...", i++, total); ehcache.put(new Element(new SimpleKey("servicios", false, false), kmlService.getAllStagesKml("servicios", false, false), true)); log.info("Caching KML {}/{}...", i++, total); ehcache.put(new Element(new SimpleKey("servicios", false, true), kmlService.getAllStagesKml("servicios", false, true), true)); log.info("Caching KML {}/{}...", i++, total); ehcache.put(new Element(new SimpleKey("servicios", true, false), kmlService.getAllStagesKml("servicios", true, false), true)); log.info("Caching KML {}/{}...", i++, total); ehcache.put(new Element(new SimpleKey("servicios", true, true), kmlService.getAllStagesKml("servicios", true, true), true)); log.info("Caching done!"); }
@Override public int size() { if (springCache.getNativeCache() instanceof Ehcache) { Ehcache ehcache = (Ehcache) springCache.getNativeCache(); return ehcache.getSize(); } throw new UnsupportedOperationException("invoke spring cache abstract size method not supported"); }
@Override public Set keys() { if (springCache.getNativeCache() instanceof Ehcache) { Ehcache ehcache = (Ehcache) springCache.getNativeCache(); return new HashSet(ehcache.getKeys()); } throw new UnsupportedOperationException("invoke spring cache abstract keys method not supported"); }
@Override protected Cache getMissingCache(String name) { // Check the EhCache cache again (in case the cache was added at runtime) Ehcache ehcache = getCacheManager().getEhcache(name); if (ehcache != null) { return new EhCacheCache(ehcache); } return null; }
@Override protected Cache createCache(final String name) { Ehcache ehcache = ehCacheManager.getEhcache(name); if (ehcache == null) { ehCacheManager.addCache(name); ehcache = ehCacheManager.getEhcache(name); } return new EhCacheCache(ehcache); }
public int getCacheSize() { int cacheSize = 0; String[] cacheNames = cacheManager.getCacheNames(); if (cacheNames != null) { for (String cacheName : cacheNames) { Ehcache cache = cacheManager.getEhcache(cacheName); if (cache != null) { cacheSize += cache.getSize(); } } } return cacheSize; }
/** * 更新点击数 */ @SuppressWarnings("unchecked") private void updateHits() { Ehcache cache = cacheManager.getEhcache(Article.HITS_CACHE_NAME); List<Long> ids = cache.getKeys(); for (Long id : ids) { Article article = articleDao.find(id); if (article != null) { Element element = cache.get(id); long hits = (Long) element.getObjectValue(); article.setHits(hits); articleDao.merge(article); } } }
/** * 更新点击数 */ @SuppressWarnings("unchecked") private void updateHits() { Ehcache cache = cacheManager.getEhcache(Product.HITS_CACHE_NAME); List<Long> ids = cache.getKeys(); for (Long id : ids) { Product product = productDao.find(id); if (product != null) { productDao.lock(product, LockModeType.PESSIMISTIC_WRITE); Element element = cache.get(id); long hits = (Long) element.getObjectValue(); long increment = hits - product.getHits(); Calendar nowCalendar = Calendar.getInstance(); Calendar weekHitsCalendar = DateUtils.toCalendar(product.getWeekHitsDate()); Calendar monthHitsCalendar = DateUtils.toCalendar(product.getMonthHitsDate()); if (nowCalendar.get(Calendar.YEAR) != weekHitsCalendar.get(Calendar.YEAR) || nowCalendar.get(Calendar.WEEK_OF_YEAR) > weekHitsCalendar.get(Calendar.WEEK_OF_YEAR)) { product.setWeekHits(increment); } else { product.setWeekHits(product.getWeekHits() + increment); } if (nowCalendar.get(Calendar.YEAR) != monthHitsCalendar.get(Calendar.YEAR) || nowCalendar.get(Calendar.MONTH) > monthHitsCalendar.get(Calendar.MONTH)) { product.setMonthHits(increment); } else { product.setMonthHits(product.getMonthHits() + increment); } product.setHits(hits); product.setWeekHitsDate(new Date()); product.setMonthHitsDate(new Date()); productDao.merge(product); } } }