English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
CacheC'est-à-dire stocker les objets souvent appelés par le programme ou le système en mémoire, de sorte que lors de leur utilisation, ils peuvent être appelés rapidement sans créer de nouvelles instances répétées. Cela peut réduire les coûts du système et améliorer l'efficacité du système.
Le cache peut principalement être divisé en deux catégories :
Première partie : cache par fichier, comme son nom l'indique, le cache par fichier consiste à stocker les données sur le disque dur, peu importe que ce soit sous format XML, fichier sérialisé DAT ou autre format de fichier.
Deuxième partie : cache en mémoire, c'est-à-dire implémenter une Map statique dans une classe, effectuer des opérations courantes sur cette Map.
import java.util.*; //Description : Gestion du cache //Fonctionnalité extensible : lorsque le cache atteint la capacité maximale de la mémoire, il est nécessaire de supprimer les objets de cache les plus anciens, ce qui nécessite de conserver le temps de création de chaque objet de cache public class CacheManager { private static HashMap cacheMap = new HashMap(); //Constructeur d'instance unique private CacheManager() { super(); } //Obtenir le cache de valeur booléenne 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); } return 0; } } //Définir le cache de valeur booléenne public synchronized static boolean setSimpleFlag(String key,boolean flag){ if (flag && getSimpleFlag(key)) {//Si vrai, il ne peut pas être remplacé 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; } } //Obtenir le cache. Méthode statique synchronisée private synchronized static Cache getCache(String key) { return (Cache) cacheMap.get(key); } //Vérifier l'existence d'un cache private synchronized static boolean hasCache(String key) { return cacheMap.containsKey(key); } //Supprimer tous les caches public synchronized static void clearAll() { cacheMap.clear(); } //Supprimer un certain type de cache spécifique en parcourant tous les objets sous HASHMAP pour déterminer si sa clé correspond au TYPE fourni 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)) { //如果匹配则删除掉 arr.add(key); } } for (int k = 0; k < arr.size(); k++) { clearOnly(arr.get(k)); } } 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); } //判断缓存是否终止 public static boolean cacheExpired(Cache cache) { if (null == cache) { //传入的缓存不存在 return false; } long nowDt = System.currentTimeMillis(); //系统当前的毫秒数 long cacheDt = cache.getTimeOut(); //缓存内的过期毫秒数 if (cacheDt <= 0||cacheDt>nowDt) { //过期时间小于等于零时,或者过期时间大于当前时间时,则为FALSE return false; } //大于过期时间 即过期 return true; } } //获取缓存中的大小 public static int getCacheSize() { return cacheMap.size(); } //获取指定的类型的大小 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) { //如果匹配则删除掉 k++; } } } ex.printStackTrace(); } return k; } //获取缓存对象中的所有键值名称 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()); } } return a; } } //获取缓存对象中指定类型的键值名称 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); } } } 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("Taille avant suppression : ");+CacheManager.getCacheSize()); // CacheManager.getCacheAllkey(); // CacheManager.clearAll("aaaa"); // System.out.println("Taille après suppression : ");+CacheManager.getCacheSize()); // CacheManager.getCacheAllkey(); } }
Voici la totalité du contenu de cet article, j'espère qu'il vous aidera dans vos études, et j'espère que vous soutiendrez également le tutoriel de cri.
Déclaration : le contenu de cet article est extrait du réseau, propriété de l'auteur original, contribué et téléchargé par les utilisateurs d'Internet, ce site n'en possède pas la propriété, n'a pas été édité par l'homme, et n'assume pas la responsabilité des responsabilités juridiques associées. Si vous trouvez du contenu suspect de violation de droits d'auteur, veuillez envoyer un e-mail à : notice#oldtoolbag.com (veuillez remplacer # par @ lors de l'envoi d'un e-mail pour signaler une violation, et fournir des preuves pertinentes. Une fois vérifié, ce site supprimera immédiatement le contenu suspect de violation de droits d'auteur.