English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
CacheIsso é armazenar os objetos que o programa ou o sistema chama frequentemente na memória, para que possam ser chamados rapidamente ao usá-los, sem a necessidade de criar novas instâncias repetidas. Isso pode reduzir o custo do sistema e melhorar a eficiência do sistema.
O cache pode ser dividido em duas grandes categorias:
Um: cache através de arquivo, conforme o nome sugere, o cache de arquivo se refere a armazenar dados no disco rígido, seja em formato XML, arquivo serializado DAT ou outro formato de arquivo;
Dois: cache de memória, ou seja, implementar um Map estático em uma classe, realizar operações comuns de adição, exclusão e consulta para esse Map.
import java.util.*; //Descrição: Gerenciamento de cache //Função expandível: quando o cache atinge o limite de memória, é necessário excluir alguns dos objetos de cache mais antigos, o que requer que cada objeto de cache preserve o tempo de criação. public class CacheManager { private static HashMap cacheMap = new HashMap(); //Método construtor de instância única private CacheManager() { super(); } //Obter cache de valor booleano public static boolean getSimpleFlag(String key){ try{ return (Boolean) cacheMap.get(key); } return false; } } public static long getServerStartdt(String key){ try { return (Long)cacheMap.get(key); } catch (Exception ex) { return 0; } } //Definir cache de valor booleano public synchronized static boolean setSimpleFlag(String key, boolean flag){ if (flag && getSimpleFlag(key)) {//Se verdadeiro, não permite que seja substituído return false; } else { cacheMap.put(key, flag); return true; } } public synchronized static boolean setSimpleFlag(String key, long serverbegrundt){ if (cacheMap.get(key) == null) { cacheMap.put(key, serverbegrundt); return true; } else { return false; } } //Obter o cache. Método sincronizado estático private synchronized static Cache getCache(String key) { return (Cache) cacheMap.get(key); } //Verificar se existe um cache private synchronized static boolean hasCache(String key) { return cacheMap.containsKey(key); } //Limpar todos os caches public synchronized static void clearAll() { cacheMap.clear(); } //Limpar um cache específico de um tipo, percorrendo todos os objetos no HASHMAP para verificar se a chave coincide com o TYPE fornecido public synchronized static void clearAll(String type) { Iterator i = cacheMap.entrySet().iterator(); String key; ArrayList arr = new ArrayList() try { while (i.hasNext()) { java.util.Map.Entry entry = (java.util.Map.Entry) i.next(); key = (String) entry.getKey(); if (key.startsWith(type)) { //Se houver correspondência, remova arr.add(key); } } for (int k = 0; k < arr.size(); k++) { clearOnly(arr.get(k)); } } catch (Exception ex) { ex.printStackTrace(); } } //清除指定的缓存 public synchronized static void clearOnly(String key) { cacheMap.remove(key); } //载入缓存 public synchronized static void putCache(String key, Cache obj) { cacheMap.put(key, obj); } //获取缓存信息 public static Cache getCacheInfo(String key) { if (hasCache(key)) { Cache cache = getCache(key); if (cacheExpired(cache)) { //调用判断是否终止方法 cache.setExpired(true); } return cache; }else return null; } //载入缓存信息 public static void putCacheInfo(String key, Cache obj, long dt,boolean expired) { Cache cache = new Cache(); cache.setKey(key); cache.setTimeOut(dt + System.currentTimeMillis()); //设置多久后更新缓存 cache.setValue(obj); cache.setExpired(expired); //缓存默认载入时,终止状态为FALSE cacheMap.put(key, cache); } //重写载入缓存信息方法 public static void putCacheInfo(String key, Cache obj, long dt){ Cache cache = new Cache(); cache.setKey(key); cache.setTimeOut(dt+System.currentTimeMillis()); cache.setValue(obj); cache.setExpired(false); cacheMap.put(key, cache); } //Determinar se o cache foi encerrado public static boolean cacheExpired(Cache cache) { if (null == cache) { //Cache传入不存在 return false; } long nowDt = System.currentTimeMillis(); //Milissegundos do sistema atual long cacheDt = cache.getTimeOut(); //Milissegundos de expiração no cache if (cacheDt <= 0 || cacheDt > nowDt) { //Se o tempo de expiração for menor ou igual a zero, ou se for maior que o tempo atual, então é FALSE return false; } else { //Se for maior que o tempo de expiração, considera-se expirado return true; } } //Obter o tamanho do cache public static int getCacheSize() { return cacheMap.size(); } //Obter o tamanho específico do tipo public static int getCacheSize(String type) { int k = 0; Iterator i = cacheMap.entrySet().iterator(); String key; try { while (i.hasNext()) { java.util.Map.Entry entry = (java.util.Map.Entry) i.next(); key = (String) entry.getKey(); if (key.indexOf(type) != -1) { //Se houver correspondência, remova k++; } } } catch (Exception ex) { ex.printStackTrace(); } return k; } //Obter todos os nomes dos valores das chaves no objeto de cache public static ArrayList getCacheAllkey() { ArrayList a = new ArrayList(); try { Iterator i = cacheMap.entrySet().iterator(); while (i.hasNext()) { java.util.Map.Entry entry = (java.util.Map.Entry) i.next(); a.add((String) entry.getKey()); } catch (Exception ex) {} finally { return a; } } //Obter o nome do valor da chave específica no objeto de cache public static ArrayList getCacheListkey(String type) { ArrayList a = new ArrayList(); String key; try { Iterator i = cacheMap.entrySet().iterator(); while (i.hasNext()) { java.util.Map.Entry entry = (java.util.Map.Entry) i.next(); key = (String) entry.getKey(); if (key.indexOf(type) != -1) { a.add(key); } } catch (Exception ex) {} finally { return a; } } } package lhm.hcy.guge.frameset.cache; public class Cache { private String key;//缓存ID private Object value;//缓存数据 private long timeOut;//更新时间 private boolean expired; //是否终止 public Cache() { super(); } public Cache(String key, Object value, long timeOut, boolean expired) { this.key = key; this.value = value; this.timeOut = timeOut; this.expired = expired; } public String getKey() { return key; } public long getTimeOut() { return timeOut; } public Object getValue() { return value; } public void setKey(String string) { key = string; } public void setTimeOut(long l) { timeOut = l; } public void setValue(Object object) { value = object; } public boolean isExpired() { return expired; } public void setExpired(boolean b) { expired = b; } } //测试类, class Test { public static void main(String[] args) { System.out.println(CacheManager.getSimpleFlag("alksd")); // CacheManager.putCache("abc", new Cache()); // CacheManager.putCache("def", new Cache()); // CacheManager.putCache("ccc", new Cache()); // CacheManager.clearOnly(""); // Cache c = new Cache(); // for (int i = 0; i < 10; i++) { // CacheManager.putCache(""); + i, c); // } // CacheManager.putCache("aaaaaaaa", c); // CacheManager.putCache("abchcy;alskd", c); // CacheManager.putCache("cccccccc", c); // CacheManager.putCache("abcoqiwhcy", c); // System.out.println("Tamanho antes da exclusão:")+CacheManager.getCacheSize()); // CacheManager.getCacheAllkey(); // CacheManager.clearAll("aaaa"); // System.out.println("Tamanho após a exclusão:")+CacheManager.getCacheSize()); // CacheManager.getCacheAllkey(); } }
Isso é tudo o que há no artigo. Espero que ajude na sua aprendizagem e que você apóie o Tutorial Yell.
Declaração: o conteúdo deste artigo é extraído da Internet, pertence ao autor original, foi submetido e carregado pelos usuários da Internet, este site não possui direitos de propriedade, não foi editado manualmente e não assume responsabilidades legais. Se você encontrar conteúdo suspeito de infringir direitos autorais, por favor, envie e-mail para: notice#oldtoolbag.com (ao enviar e-mail, substitua # por @ para denunciar e forneça provas. Se confirmado, o site deletará imediatamente o conteúdo suspeito de infringir direitos autorais.)