@Around("simplePointcut()") public Object aroundLogCalls(ProceedingJoinPoint joinPoint) throws Throwable { String targetName = joinPoint.getTarget().getClass().toString(); String methodName = joinPoint.getSignature().getName(); Object[] arguments = joinPoint.getArgs(); // 试图得到标注的Ehcache类 @SuppressWarnings("unused") Method[] methods = joinPoint.getTarget().getClass().getMethods(); Ehcache flag = null; for (Method m : methods) { if (m.getName().equals(methodName)) { Class[] tmpCs = m.getParameterTypes(); if (tmpCs.length == arguments.length) { flag = m.getAnnotation(Ehcache.class); break; } } } if (flag == null) { return null; } // Ehcache flag // =joinPoint.getTarget().getClass().getMethod(methodName).getAnnotation(Ehcache.class); Object result; String cacheKey = getCacheKey(targetName, methodName, arguments); Element element = null; if (flag.eternal()) { // 永久缓存 element = dictCache.get(cacheKey); } else { // 临时缓存 element = eternalCache.get(cacheKey); } if (element == null) { if ((arguments != null) && (arguments.length != 0)) { result = joinPoint.proceed(arguments); } else { result = joinPoint.proceed(); } element = new Element(cacheKey, (Serializable) result); if (flag.eternal()) { // 永久缓存 dictCache.put(element); } else { // 临时缓存 eternalCache.put(element); } } return element.getValue(); }
@Override public void update(Client entity) { // TODO Auto-generated method stub if (cache != null) { if (cache.isKeyInCache(entity.getEmail())) { cache.acquireWriteLockOnKey(entity.getEmail()); cache.remove(entity.getEmail()); cache.put(new Element(entity.getEmail(), entity)); cache.releaseWriteLockOnKey(entity.getEmail()); } else cache.put(new Element(entity.getEmail(), entity)); } }
@Override protected void runTest(Cache cache, Toolkit clusteringToolkit) throws Throwable { cache = cacheManager.getCache("testEventual"); int size = 40 * 1024 * 1024; byte[] b = new byte[size]; long time = System.currentTimeMillis(); cache.put(new Element(1, b)); while (cache.calculateInMemorySize() < size) { Thread.sleep(1); } time = System.currentTimeMillis() - time; System.err.println( "time taken = " + time + " " + cache.calculateOffHeapSize() + " " + cache.calculateInMemorySize()); }
@Test public void testConfigFileHonorsClusteringOff() { final CacheManager cacheManager = new CacheManager( CacheManager.class.getResourceAsStream("/terracotta/ehcache-event-replication.xml")); try { final Cache cache = cacheManager.getCache("replication"); assertThat(cache, notNullValue()); final TerracottaConfiguration terracottaConfiguration = cache.getCacheConfiguration().getTerracottaConfiguration(); assertThat(terracottaConfiguration, notNullValue()); assertThat(terracottaConfiguration.isClustered(), is(false)); final List eventListenerConfigurations = cache.getCacheConfiguration().getCacheEventListenerConfigurations(); assertThat(eventListenerConfigurations, notNullValue()); assertThat(eventListenerConfigurations.size(), is(1)); assertThat( ((CacheConfiguration.CacheEventListenerFactoryConfiguration) eventListenerConfigurations.get(0)) .getFullyQualifiedClassPath(), equalTo(TerracottaCacheEventReplicationFactory.class.getName())); cache.put(new Element("key", "value")); assertThat((String) cache.get("key").getValue(), equalTo("value")); } finally { cacheManager.shutdown(); } }
/** * Gets a parsed query for the passed in parameters. If the ParsedQuery requested has already been * created on this app node, it will retrieve it from a cache instead of recreating it. Use this * method instead of parseQuery if a cached copy is acceptable (almost always). * * @param db Database that the query will run against * @param toParse Query to be parsed. * @param session Database session. * @return a PreparedStatement to use. */ public static ParsedQuery getParsedQuery(String db, Query toParse, Session session) throws FieldNotIndexedException { if (db == null || db.trim().equals("")) { throw new IllegalArgumentException("Query must be populated."); } if (toParse == null) { throw new IllegalArgumentException("Query cannot be null."); } final String key = db + ":" + toParse.getTable() + ":" + toParse.getWhere(); // StopWatch pull = new StopWatch(); // pull.start(); Cache c = CacheFactory.getCache("parsedQuery"); // synchronized (CacheSynchronizer.getLockingObject(key, ParsedQuery.class)) // { Element e = c.get(key); // pull.stop(); // logger.debug("Time to pull a parsed query from cache: " + pull.getTime()); if (e == null) { logger.debug("Creating new ParsedQuery for: " + key); // StopWatch sw = new StopWatch(); // sw.start(); e = new Element(key, parseQuery(db, toParse, session)); c.put(e); // sw.stop(); // logger.debug("Time to create a new parsed query: " + sw.getTime()); } else { logger.trace("Pulling ParsedQuery from Cache: " + e.getObjectValue().toString()); } return (ParsedQuery) e.getObjectValue(); // } }
/** 主方法 如果某方法可被缓存就缓存其结果 方法结果必须是可序列化的(serializable) */ public Object invoke(MethodInvocation invocation) throws Throwable { String targetName = invocation.getThis().getClass().getName(); String methodName = invocation.getMethod().getName(); Object[] arguments = invocation.getArguments(); Object result; logger.info("在缓存中查找方法返回的对象!"); String cacheKey = getCacheKey(targetName, methodName, arguments); Element element = cache.get(cacheKey); if (element == null) { logger.info("正在拦截方法!"); result = invocation.proceed(); logger.info("正在缓存对象!"); element = new Element(cacheKey, (Serializable) result); cache.put(element); } return element.getValue(); }
/** * Checks whether the {@code Cache} is activated and in case it is activated, all {@link Task}s of * the given {@link ResultSet}, which are loaded for the present time, will be put in the {@code * Cache}. * * @param resultSet The {@code ResultSet} with the {@code Task}s */ private void putTasksIntoCache(ResultSetImpl<TaskID, Task> resultSet) { if (cacheActivated) { for (Task task : resultSet.getLoadedData()) { cache.put(new Element(task.getID(), task)); } } }
/** 拦截 Service/DAO 的方法,并查找该结果是否存在,如果存在就返回 cache 中的值, 否则,返回数据库查询结果,并将查询结果放入 cache */ @Override public Object invoke(MethodInvocation invocation) throws Throwable { String targetName = invocation.getThis().getClass().getName(); String methodName = invocation.getMethod().getName(); Object[] arguments = invocation.getArguments(); Object result; String cacheKey = getCacheKey(targetName, methodName, arguments); logger.info("从[" + cache.getName() + "]查询key:[" + cacheKey + "]的缓存]"); // System.out.println("从["+cache.getName()+"]查询key:["+cacheKey+"]的缓存]"); Element element = cache.get(cacheKey); if (element == null) { result = invocation.proceed(); logger.info("key:[" + cacheKey + "]无缓存,创建缓存为[" + result + "]"); // System.out.println("key:["+cacheKey+"]无缓存,创建缓存为["+result+"]"); element = new Element(cacheKey, (Serializable) result); cache.put(element); } return element.getObjectValue(); }
public <T extends ISocioObject> void saveObject(T object) throws DuplicateMySocioObjectException { if (object instanceof IUniqueObject) { IUniqueObject uniqueObject = (IUniqueObject) object; Cache cache = cm.getCache("Objects"); String key = uniqueObject.getUniqueFieldName() + uniqueObject.getUniqueFieldValue(); Element element = cache.get(key); if (element != null) { ((SocioObject) object).setId((ObjectId) element.getValue()); return; } @SuppressWarnings("unchecked") Query<T> q = (Query<T>) ds.createQuery(object.getClass()) .field(uniqueObject.getUniqueFieldName()) .equal(uniqueObject.getUniqueFieldValue()); T objectT = (T) q.get(); if (objectT != null) { ((SocioObject) object).setId(objectT.getId()); element = new Element(key, objectT.getId()); cache.put(element); logger.info( "Duplicate object of type: " + object.getClass() + " for query: " + q.toString()); throw new DuplicateMySocioObjectException( "Duplicate object of type: " + object.getClass() + " for query: " + q.toString()); } } ds.save(object); }
/** * Test. * * @throws IOException e */ @Test public void testCache() throws IOException { final String cacheName = "test 1"; final CacheManager cacheManager = CacheManager.getInstance(); cacheManager.addCache(cacheName); 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); } }
@Override public Task getTask(TaskID taskID, boolean loadCompletely, boolean forceAPICall) { if (taskID == null) { throw new NullPointerException(); } Task task; if (cacheActivated) { if (!forceAPICall) { Element element = cache.get(taskID); if (element != null) { task = (Task) element.getObjectValue(); if (loadCompletely && !((Cachable) task).isCompletelyLoaded()) { task = getDataFactory().getTask(taskID, loadCompletely); } } else { task = getDataFactory().getTask(taskID, loadCompletely); } } else { task = getDataFactory().getTask(taskID, loadCompletely); } if (task != null) { cache.put(new Element(task.getID(), task)); } } else { task = getDataFactory().getTask(taskID, loadCompletely); } return task; }
@Override protected void runTest(Cache cache, Toolkit clusteringToolkit) throws Throwable { int size = cache.getSize(); assertEquals(0, size); System.out.println("Client populating cache."); for (int i = 0; i < 7000; i++) { cache.put(new Element("key-" + i, "value-" + i)); } System.out.println("Cache populate. Size: " + cache.getSize()); // assert range as some may already have got evicted while populating // eviction is aggressive with new impl based on "evictUnexpiredEntries" with true by default assertRange(5000, 7000, cache); System.out.println("Sleeping for 3 mins (now=" + new Date() + ") ... "); // Sleep for TTI to kick in: Thread.sleep(3 * 60 * 1000); System.out.println("After sleeping 3 mins. Size: " + cache); // Now size should be equal to capacity assertRange(3000, 6000, cache); System.out.println("Trying to get on all elements, inline eviction should happen"); // all others should be evicted inline for (int i = 0; i < 7000; i++) { Element element = cache.get("key-" + i); Assert.assertNull("Element should be null of key-" + i, element); } Thread.sleep(5 * 1000); System.out.println("After inline eviction. Size: " + cache.getSize()); // Now size should be equal to 0 assertEquals(0, cache.getSize()); }
@Override public void doResponse() { // TODO Auto-generated method stub try { String platform = request.getParameter("p"); platform = platform == null ? "android" : platform; String cacheIndex = REQUEST_TYPE + ",p:" + platform; UtilFunctions.serverLog("cacheIndex:" + cacheIndex); String responseData = null; Element element = null; if ((element = cache.get(cacheIndex)) != null /*cache.isKeyInCache(cacheIndex)*/) { responseData = (String) element.getValue(); // System.out.println(REQUEST_TYPE+":缓存数据"); UtilFunctions.serverLog(REQUEST_TYPE + CACHE_DATA); } else { VersionService versionService = (VersionService) context.getBean("versionService"); Version version = versionService.getLatestVersion( platform == null ? VersionService.PLATFORM_ANDROID : platform); if (version == null) { UtilFunctions.serverLog(REQUEST_TYPE + "version is null"); return; } responseData = version.getJSONObject().toString(); cache.put(new Element(cacheIndex, responseData)); // System.out.println(REQUEST_TYPE+":非缓存数据"); UtilFunctions.serverLog(REQUEST_TYPE + NOT_CACHE_DATA); } PrintWriter pw = response.getWriter(); pw.write(responseData); pw.close(); } catch (IOException e) { e.printStackTrace(); } }
@Around("findAllComPendendias()") public Object findAllTurmasComPendenciasMethodInterceptor(ProceedingJoinPoint joinPoint) throws Throwable { Object result = null; CacheManager cacheManager = CacheManager.create(new ClassPathResource("echache.xml").getInputStream()); Cache cache = cacheManager.getCache("turmas-pendencias-cache"); Object[] args = joinPoint.getArgs(); if (args[0] == null || args[1] == null) { result = joinPoint.proceed(); return result; } SimpleDateFormat df = new SimpleDateFormat("yyyy"); String exercicio = df.format((Date) args[0]); String organizacao = ((Long) args[1]).toString(); String key = exercicio + "-" + organizacao; Element element = cache.get(key); if (element == null) { result = joinPoint.proceed(); cache.put(new Element(key, result)); } else { Logger.getLogger(this.getClass().getName()) .log(Level.INFO, "Dados presentes no cache, não foi necessário acesso ao banco de dados"); result = element.getValue(); } return result; }
@Around("findTurmaEfetiva()") public Object findTurmaEfetivaMethodInterceptor(ProceedingJoinPoint joinPoint) throws Throwable { Object result = null; CacheManager cacheManager = CacheManager.create(new ClassPathResource("echache.xml").getInputStream()); Cache cache = cacheManager.getCache("turmas-efetivas-cache"); Object[] args = joinPoint.getArgs(); Long turmaId = (Long) args[0]; Element element = cache.get(turmaId); if (element == null) { result = joinPoint.proceed(); cache.put(new Element(turmaId, result)); } else { Logger.getLogger(this.getClass().getName()) .log( Level.INFO, "Dados presentes no cache de turmas, não foi necessário acesso ao banco de dados"); result = element.getValue(); } return result; }
@Override public <T extends GeneralMessage> boolean isNewMessage(String userId, T message, Class<T> T) { Cache cache = cm.getCache("Messages"); String key = message.getUniqueFieldValue() + userId; Element element = cache.get(key); if (element != null) { return (Boolean) element.getValue(); } Query<UnreaddenMessage> isUnread = ds.createQuery(UnreaddenMessage.class) .field("userId") .equal(userId) .field("message") .equal(new Key<T>(T, message.getId())); Query<ReaddenMessage> isRead = ds.createQuery(ReaddenMessage.class) .field("userId") .equal(userId) .field("messageUniqueId") .equal(message.getUniqueFieldValue().toString()); Boolean newMessage = isUnread.countAll() <= 0 && isRead.countAll() <= 0; element = new Element(key, new Boolean(false)); cache.put(element); return newMessage; }
public static void main(String args[]) { Map<Object, Element> map = new HashMap<Object, Element>(); List<String> list = new ArrayList<String>(); // Create a cache manager CacheManager cacheManager = CacheManager.getInstance(); // Creates a cache called newCache cacheManager.addCache("newCache"); // Get cache called newCache Cache cache = cacheManager.getCache("newCache"); StatisticsGateway stats = cache.getStatistics(); // put into cache cache.put(new Element("1", "Monday")); list.add("1"); cache.put(new Element("2", "Tuesday")); list.add("2"); cache.put(new Element("3", "Wednesday")); list.add("3"); cache.put(new Element("4", "Thursday")); list.add("4"); // Displaying all elements System.out.println("All elements"); map = cache.getAll(list); Iterator it = map.entrySet().iterator(); while (it.hasNext()) { Map.Entry pair = (Map.Entry) it.next(); System.out.println(pair.getKey() + " = " + pair.getValue()); } // Displaying elements and size of cache Element element = cache.get("1"); System.out.println("Value of key 1 :" + element.getObjectValue().toString()); System.out.println("Cache Size " + cache.getSize()); element = cache.get("2"); System.out.println("Value of key 2 :" + element.getObjectValue().toString()); System.out.println("Cache Size " + cache.getSize()); cache.removeElement(element); System.out.println("Cache Size after removing an element : " + cache.getSize()); cache.flush(); System.out.println("Removed Cache with key 3 :" + cache.remove("3")); System.out.println("Size after remove : " + cache.getSize()); }
@Override public void put(K key, V value) { if (key == null) { throw new IllegalArgumentException("key can't be null."); } Element element = new Element(key, value); cache.put(element); }
public void replace(String key, Object value, int expiration) { if (cache.get(key) == null) { return; } Element element = new Element(key, value); element.setTimeToLive(expiration); cache.put(element); }
@Override public void loadRightsToCache(Integer uid) { adminRightsCache.remove(uid); Set<String> rights = permissionSvc.getItems(uid); if (!rights.isEmpty()) { adminRightsCache.put(new Element(uid, rights)); } }
protected void cacheIdentifiers( final UniqueId uniqueId, final Pair<ExternalIdBundle, VersionCorrection> key) { synchronized (_eidToUidCache) { final Element e = _eidToUidCache.get(key); if (e == null) { _eidToUidCache.put(new Element(key, uniqueId)); } } }
@Override public void initCache() { userCache.removeAll(); List<UserEntity> userList = userService.queryAllUsers(); for (UserEntity user : userList) { userCache.put(new Element(user.getUserId(), new Cache(user.getUserId(), user))); } }
public void put(Object key, Object pValue) throws CacheException { try { Element element = new Element((Serializable) key, (Serializable) pValue); ehcache.put(element); } catch (IllegalArgumentException e) { throw new CacheException(e); } catch (IllegalStateException e) { throw new CacheException(e); } }
@Override public boolean cacheBO(byte[] bo, String hashOfBO) { Element element = new Element(hashOfBO, bo); try { cache.put(element); return true; } catch (Exception ex) { LOG.warn("Put not succeeded"); return false; } }
public synchronized long incr(String key, int by) { Element e = cache.get(key); if (e == null) { return -1; } long newValue = ((Number) e.getValue()).longValue() + by; Element newE = new Element(key, newValue); newE.setTimeToLive(e.getTimeToLive()); cache.put(newE); return newValue; }
@Override public void updateBounceProxy(BounceProxyRecord bpRecord) throws IllegalArgumentException { if (log.isTraceEnabled()) { log.trace("updateBounceProxy {} in cache {}", bpRecord.getBounceProxyId(), cacheName); tracePeers(); } Cache cache = manager.getCache(cacheName); Element element = new Element(bpRecord.getBounceProxyId(), bpRecord); cache.put(element); }
@Test public void whenNotifiedOfLogInThenTopUpResultStatusShouldBeRemovedFromCache() { Element element = new Element( PLAYER_ID, new TopUpResultService.TopUpStatusCacheEntry(ACKNOWLEDGED, new DateTime())); topUpStatusCache.put(element); assertNotNull(topUpStatusCache.get(PLAYER_ID)); underTest.clearTopUpStatus(PLAYER_ID); assertNull(topUpStatusCache.get(PLAYER_ID)); }
public Object put(Object key, Object value) { // Multiple steps done to satisfy Cache API requirement for Previous object return. Element elem = null; Object previous = null; elem = ehcache.get(key); if (elem != null) { previous = elem.getObjectValue(); } elem = new Element(key, value); ehcache.put(elem); return previous; }
@Override public void addBounceProxy(ControlledBounceProxyInformation bpInfo) throws IllegalArgumentException { if (log.isTraceEnabled()) { log.trace("addBounceProxy {} to cache {}", bpInfo.getId(), cacheName); tracePeers(); } Cache cache = manager.getCache(cacheName); Element element = new Element(bpInfo.getId(), new BounceProxyRecord(bpInfo)); cache.put(element); }
@Override public ManageableSecurity loadSecurityDetail(ManageableSecurity base) { ManageableSecurity cached; Element e = _detailsCache.get(base.getUniqueId()); if (e != null) { cached = (ManageableSecurity) e.getValue(); } else { cached = _underlying.loadSecurityDetail(base); e = new Element(base.getUniqueId(), cached); _detailsCache.put(e); } return JodaBeanUtils.clone(cached); }