English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Implementación del mecanismo de caché común en Java

CacheEsto es almacenar los objetos que el programa o el sistema llama con frecuencia en la memoria, para que puedan ser llamados rápidamente cuando se necesiten, sin tener que crear nuevas instancias repetidas. Esto puede reducir los costos del sistema y aumentar la eficiencia del sistema.

El cache se puede dividir principalmente en dos grandes categorías:   

1. A través del cache de archivo, como su nombre indica, el cache de archivo se refiere a almacenar los datos en el disco, ya sea en formato XML, archivo de serialización DAT o cualquier otro formato de archivo 

2. Caché de memoria, es decir, implementar un Map estático en una clase, realizar operaciones de adición, eliminación y búsqueda comunes en este Map

import java.util.*; 
 //Descripción: Gestión de cache 
 //La función expandible: cuando la memoria del cache se llena, es necesario eliminar algunos objetos de cache más antiguos, lo que requiere que se guarde el tiempo de creación de cada objeto de cache 
public class CacheManager { 
 private static HashMap cacheMap = new HashMap(); 
 //Método constructor de instancia única 
 private CacheManager() { 
  super(); 
 } 
 //Obtener el caché 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; 
  } 
 } 
 //Establecer el caché de valor booleano 
 public synchronized static boolean setSimpleFlag(String key,boolean flag){ 
  if (flag && getSimpleFlag(key)) {//Si es verdadero, no se permite que se sobrescriba 
   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; 
  } 
 } 
 //Obtener el caché. Método sincronizado estático 
 private synchronized static Cache getCache(String key) { 
  return (Cache) cacheMap.get(key); 
 } 
 //Determinar si existe un caché 
 private synchronized static boolean hasCache(String key) { 
  return cacheMap.containsKey(key); 
 } 
 //Eliminar todos los cachés 
 public synchronized static void clearAll() { 
  cacheMap.clear(); 
 } 
 //Eliminar todos los cachés específicos de un tipo, recorriendo todos los objetos bajo el HASHMAP para determinar si su KEY coincide con el TYPE proporcionado 
 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)) { //Si coincide, eliminarlo 
     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 si el caché ha finalizado 
 public static boolean cacheExpired(Cache cache) { 
  if (null == cache) { //El caché entrante no existe 
   return false; 
  } 
  long nowDt = System.currentTimeMillis(); //Milisegundos del sistema actual 
  long cacheDt = cache.getTimeOut(); //Milisegundos de expiración en el caché 
  if (cacheDt <= 0||cacheDt>nowDt) { //Cuando la hora de expiración es menor o igual a cero, o cuando la hora de expiración es mayor que el tiempo actual, es FALSE 
   return false; 
  } else { //Mayor que la hora de expiración, es decir, ha expirado 
   return true; 
  } 
 } 
 //Obtener el tamaño del caché 
 public static int getCacheSize() { 
  return cacheMap.size(); 
 } 
 //Obtener el tamaño específico del 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) { //Si coincide, eliminarlo 
     k++; 
    } 
   } 
  } catch (Exception ex) { 
   ex.printStackTrace(); 
  } 
  return k; 
 } 
 //Obtener todos los nombres de valores de claves del objeto de caché 
 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; 
  } 
 } 
 //Obtener el nombre del valor de la clave del objeto de caché específico del tipo 
 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; 
  } 
 } 
} 
paquete 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("El tamaño antes de la eliminación:");+CacheManager.getCacheSize()); 
//  CacheManager.getCacheAllkey(); 
//  CacheManager.clearAll("aaaa"); 
//  System.out.println("El tamaño después de la eliminación:");+CacheManager.getCacheSize()); 
//  CacheManager.getCacheAllkey(); 
 } 
}

Esto es todo el contenido de este artículo, espero que ayude en su aprendizaje y que todos apoyen a la tutoría de grito.

Declaración: el contenido de este artículo se obtiene de la red, es propiedad del autor original, el contenido se contribuye y carga de manera autónoma por los usuarios de Internet, este sitio no posee los derechos de propiedad, no ha sido editado artificialmente y no asume responsabilidades legales relacionadas. Si encuentra contenido sospechoso de infracción de derechos de autor, por favor envíe un correo electrónico a: notice#oldtoolbag.com (al enviar un correo electrónico, por favor reemplace # con @) para denunciar y proporcionar evidencia relevante. Una vez confirmado, este sitio eliminará inmediatamente el contenido sospechoso de infracción.

Te gustaría que te gustara