O cache significa que os objetos que o programa ou sistema geralmente são armazenados na memória e podem ser chamados rapidamente quando usados uma vez, sem criar novas instâncias duplicadas. Isso pode reduzir a sobrecarga do sistema e melhorar a eficiência do sistema.
Os caches podem ser divididos principalmente em duas categorias:
1. Através do cache de arquivos, como o nome implica, o cache de arquivos refere -se a armazenar dados no disco, esteja você no formato XML, formato de dados de arquivo serializado ou outros formatos de arquivo;
2. Cache de memória, ou seja, implemente mapas estáticos em uma classe e execute adições regulares, exclusão e pesquisa deste mapa.
importar java.util.*; // Descrição: Gerencie o cache // Funções extensíveis: Quando o Chche atinge o excesso de memória, alguns dos primeiros objetos de cache devem ser limpos, o que requer economizar tempo de criação para cada objeto de cache public Cachemanager {private estático hashmap Cachemap = new Hashmap (); // Construtor de instância única Cachemanager () {super (); } // Obtenha cache booleano public estático booleano getSImpleflag (chave de string) {try {return (boolean) cachemap.get (key); } catch (nullPointerException e) {return false; }} public static long getServerStartdt (chave de string) {try {return (long) Cachemap.get (key); } catch (Exceção ex) {return 0; }} // Definir cache booleano public sincronizado estático booleano setSimpleflag (tecla String, sinalizador booleano) {if (sinalizador && getSImpleflag (key)) {// Se true, o substituto não poderá ser retornado false; } else {Cachemap.put (chave, sinalizador); retornar true; }} public sincronizado estático booleano setSImpleflag (chave da string, long ServerBeGrundt) {if (cachemap.get (key) == null) {cachemap.put (chave, serverbegrundt); retornar true; } else {return false; }} // Obtenha cache. Método estático sincronizado Private Sincronizado Cache estático getCache (chave da string) {return (cache) Cachemap.get (key); } // julgue se existe um cache privado sincronizado estático booleano hascache (chave de string) {return cachemap.containskey (key); } // limpe todos os caches } // Limpe um certo tipo de cache e determine se sua chave e o tipo de entrada correspondem ao vazio estático sincronizado público (tipo de string) {iterator i = cachemap.entrySet (). Iterator (); Chave de string; Arraylist arr = new ArrayList (); tente {while (i.hasNext ()) {java.util.map.entry Entry = (java.util.map.entry) i.next (); key = (string) Entry.getKey (); if (key.startswith (type)) {// se ele corresponde, exclua arr.add (key); }} para (int k = 0; k <arr.size (); k ++) {clearonly (arr.get (k)); }} catch (Exceção ex) {ex.PrintStackTrace (); }} // limpe o cache especificado public sincronizado estático void claramente (chave de string) {cachemap.remove (key); } // Carregar o cache public sincronizado estático void putcache (chave da string, cache obj) {cachemap.put (chave, obj); } // Obtenha informações de cache public static cache getCacheInfo (chave de string) {if (hascache (key)) {cache cache = getCache (key); if (cacheexirird (cache)) {// ligue para determinar se deve encerrar o método cache.setexirired (true); } retornar cache; } mais retorna nulo; } // Carregar informações do cache public estático void putcacheInfo (chave de string, cache obj, dt longo, boolean expirado) {cache cache = new cache (); cache.setKey (chave); cache.setTimeout (dt + system.currenttimemillis ()); // Defina quanto tempo atualiza o cache cache.setValue (OBJ); cache.setexired (expirado); // Quando o cache é carregado por padrão, o status de terminação é falso Cachemap.put (chave, cache); } // Reescreva o método de informação do cache de carregamento public static void putcacheInfo (chave de string, cache obj, dt long dt) {cache cache = new cache (); cache.setKey (chave); cache.setTimeout (dt+system.currenttimemillis ()); cache.setValue (OBJ); cache.setexired (false); Cachemap.put (chave, cache); } // julgue se o cache encerra o cacheexpirado booleano estático } long nowdt = System.currenttimemillis (); // o número atual de milissegundos no sistema long cachedt = cache.getTimeout (); // O número de milissegundos expirados no cache if (cachedt <= 0 || cachedt> nowdt) {// Quando o tempo de expiração é menor ou igual a zero, ou o tempo de expiração é maior que o tempo atual, é falso retorno falso; } else {// O tempo de expiração é maior que o tempo de validade, ou seja, o retorno expirado de retorno; }} // Obtenha o tamanho do cache public static int getCachesize () {return cachemap.size (); } // Obtenha o tamanho do tipo especificado public static int getCachesize (string type) {int k = 0; Iterator i = cachemap.entrySet (). Iterator (); Chave de string; tente {while (i.hasNext ()) {java.util.map.entry Entry = (java.util.map.entry) i.next (); key = (string) Entry.getKey (); if (key.indexOF (type)! = -1) {// Se ele corresponde, exclua k ++; }}} catch (Exceção ex) {ex.printStackTrace (); } retornar k; } // Obtenha todos os nomes do valor-chave no objeto Cache Public Static ArrayList getCacheallkey () {ArrayList a = new ArrayList (); tente {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 (Exceção ex) {} finalmente {return a; }} // Obtenha o nome do valor da chave do tipo especificado no objeto de cache public static ArrayList getCachelistKey (string type) {ArrayList a = new ArrayList (); Chave de string; tente {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 (tipo)! = -1) {a.add (key); }}} catch (Exceção ex) {} finalmente {return a; }}} pacote lhm.hcy.guge.fameset.cache; classe pública Cache {private string key; // Cache ID Valor do objeto privado; // Dados de cache Timeout privado de longa data; // Atualizar tempo Privado booleano expirou; // não termina public cache () {super (); } public cache (chave da string, valor do objeto, tempo limite longo, expirado booleano) {this.key = key; this.value = value; this.timeout = timeout; this.expired = expirado; } public string getKey () {return Key; } public long getTimeout () {retornar timeout; } public object getValue () {return value; } public void setKey (string string) {key = string; } public void setTimeout (Long l) {timeout = l; } public void SetValue (objeto objeto) {value = object; } public boolean isExpired () {return expirou; } public void SetExpired (boolean b) {expirou = b; }} // classe de teste, classe teste {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 ("aaaaaaaaa", c); // cachemanager.putcache ("Abchcy; alskd", c); // cachemanager.putcache ("ccccccccc", 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 (); }}O exposto acima é todo o conteúdo deste artigo. Espero que seja útil para o aprendizado de todos e espero que todos apoiem mais o wulin.com.