Java实现缓存(类似于Redis)

Java 实现缓存,类似于 Redis 的实现,可以缓存对象到内存中,提高访问效率。代码如下:

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;

/**

  • <p>Description: 管理缓存 </p>

  • 可扩展的功能:当 cache 到内存溢出时必须清除掉最早期的一些缓存对象,这就要求对每个缓存对象保存创建时间

  • 目前该缓存管理器仅仅支持 IOS 客户端访问时的登录状态管理,如果进行它用,请防止 key 冲突

  • @author zhanglp
    */
    public class CacheManager {
    private static HashMap cacheMap = new HashMap();

    //单实例构造方法
    private CacheManager() {
    super();
    }
    //获取布尔值的缓存
    public static boolean getSimpleFlag(String key){
    try{
    return (Boolean) cacheMap.get(key);
    }
    catch(NullPointerException e){
    return false;
    }
    }
    public static long getServerStartdt(String key){
    try {
    return (Long)cacheMap.get(key);
    }
    catch (Exception ex) {
    return 0;
    }
    }
    //设置布尔值的缓存
    public synchronized static boolean setSimpleFlag(String key,boolean flag){
    if (flag && getSimpleFlag(key)) {//假如为真不允许被覆盖
    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;
    }
    }

    //得到缓存。同步静态方法
    private synchronized static Cache getCache(String key) {
    return (Cache) cacheMap.get(key);
    }

    //判断是否存在一个缓存
    private synchronized static boolean hasCache(String key) {
    return cacheMap.containsKey(key);
    }

    //清除所有缓存
    public synchronized static void clearAll() {
    cacheMap.clear();
    }

    //清除某一类特定缓存, 通过遍历 HASHMAP 下的所有对象,来判断它的 KEY 与传入的 TYPE 是否匹配
    public synchronized static void clearAll(String type) {
    Iterator i
    = cacheMap.entrySet().iterator();
    String key;
    ArrayList
    <String> arr = new ArrayList<String>();
    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));
    }
    }
    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) {

     </span><span style="color: rgba(0, 0, 255, 1)">if</span><span style="color: rgba(0, 0, 0, 1)"> (hasCache(key)) {   
         Cache cache </span>=<span style="color: rgba(0, 0, 0, 1)"> getCache(key);   
         </span><span style="color: rgba(0, 0, 255, 1)">if</span> (cacheExpired(cache)) { <span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">调用判断是否终止方法   </span>
             cache.setExpired(<span style="color: rgba(0, 0, 255, 1)">true</span><span style="color: rgba(0, 0, 0, 1)">);   
         }   
         </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> cache;   
     }</span><span style="color: rgba(0, 0, 255, 1)">else</span>  
         <span style="color: rgba(0, 0, 255, 1)">return</span> <span style="color: rgba(0, 0, 255, 1)">null</span><span style="color: rgba(0, 0, 0, 1)">;   
    

    }

    //载入缓存信息
    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;
    }
    else { //大于过期时间 即过期
    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++;
    }
    }
    }
    catch (Exception ex) {
    ex.printStackTrace();
    }

     </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> k;   
    

    }

    //获取缓存对象中的所有键值名称
    public static ArrayList<String> 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;
    }
    }

    //获取缓存对象中指定类型 的键值名称
    public static ArrayList<String> 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;
    }
    }

}

/**   
 * <p>Description: 缓存 DTO</p>  
 * @author zhanglp
 */  
public class Cache {   
        private String key;//缓存 ID   
        private Object value;//缓存数据   
        private long timeOut;//更新时间   
        private boolean expired; //是否终止   
        public Cache() {   
                super();}   
    </span><span style="color: rgba(0, 0, 255, 1)">public</span> Cache(String key, Object value, <span style="color: rgba(0, 0, 255, 1)">long</span> timeOut, <span style="color: rgba(0, 0, 255, 1)">boolean</span><span style="color: rgba(0, 0, 0, 1)"> expired) {   
            </span><span style="color: rgba(0, 0, 255, 1)">this</span>.key =<span style="color: rgba(0, 0, 0, 1)"> key;   
            </span><span style="color: rgba(0, 0, 255, 1)">this</span>.value =<span style="color: rgba(0, 0, 0, 1)"> value;   
            </span><span style="color: rgba(0, 0, 255, 1)">this</span>.timeOut =<span style="color: rgba(0, 0, 0, 1)"> timeOut;   
            </span><span style="color: rgba(0, 0, 255, 1)">this</span>.expired =<span style="color: rgba(0, 0, 0, 1)"> expired;   
    }   

    </span><span style="color: rgba(0, 0, 255, 1)">public</span><span style="color: rgba(0, 0, 0, 1)"> String getKey() {   
            </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> key;   
    }   

    </span><span style="color: rgba(0, 0, 255, 1)">public</span> <span style="color: rgba(0, 0, 255, 1)">long</span><span style="color: rgba(0, 0, 0, 1)"> getTimeOut() {   
            </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> timeOut;   
    }   

    </span><span style="color: rgba(0, 0, 255, 1)">public</span><span style="color: rgba(0, 0, 0, 1)"> Object getValue() {   
            </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> value;   
    }   

    </span><span style="color: rgba(0, 0, 255, 1)">public</span> <span style="color: rgba(0, 0, 255, 1)">void</span><span style="color: rgba(0, 0, 0, 1)"> setKey(String string) {   
            key </span>=<span style="color: rgba(0, 0, 0, 1)"> string;   
    }   

    </span><span style="color: rgba(0, 0, 255, 1)">public</span> <span style="color: rgba(0, 0, 255, 1)">void</span> setTimeOut(<span style="color: rgba(0, 0, 255, 1)">long</span><span style="color: rgba(0, 0, 0, 1)"> l) {   
            timeOut </span>=<span style="color: rgba(0, 0, 0, 1)"> l;   
    }   

    </span><span style="color: rgba(0, 0, 255, 1)">public</span> <span style="color: rgba(0, 0, 255, 1)">void</span><span style="color: rgba(0, 0, 0, 1)"> setValue(Object object) {   
            value </span>=<span style="color: rgba(0, 0, 0, 1)"> object;   
    }   

    </span><span style="color: rgba(0, 0, 255, 1)">public</span> <span style="color: rgba(0, 0, 255, 1)">boolean</span><span style="color: rgba(0, 0, 0, 1)"> isExpired() {   
            </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> expired;   
    }   

    </span><span style="color: rgba(0, 0, 255, 1)">public</span> <span style="color: rgba(0, 0, 255, 1)">void</span> setExpired(<span style="color: rgba(0, 0, 255, 1)">boolean</span><span style="color: rgba(0, 0, 0, 1)"> b) {   
            expired </span>=<span style="color: rgba(0, 0, 0, 1)"> b;   
    }   

}

 如何使用:

    public static void main(String[] args) {
    </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">Demo1</span>
    Cache c1 = <span style="color: rgba(0, 0, 255, 1)">new</span><span style="color: rgba(0, 0, 0, 1)"> Cache();
    c1.setKey(</span>"China"<span style="color: rgba(0, 0, 0, 1)">);
    c1.setValue(</span>"中华人民共和国"<span style="color: rgba(0, 0, 0, 1)">);

    Cache c2 </span>= <span style="color: rgba(0, 0, 255, 1)">new</span><span style="color: rgba(0, 0, 0, 1)"> Cache();
    c2.setKey(</span>"American"<span style="color: rgba(0, 0, 0, 1)">);
    c2.setValue(</span>"美利坚合众国"<span style="color: rgba(0, 0, 0, 1)">);
    
    CacheManager.putCache(</span>"one"<span style="color: rgba(0, 0, 0, 1)">, c1);
    CacheManager.putCache(</span>"two"<span style="color: rgba(0, 0, 0, 1)">, c2);
    System.out.println(</span>"缓存大小:"+<span style="color: rgba(0, 0, 0, 1)">CacheManager.getCacheSize());
    System.out.println(</span>"key为one的缓存对象Value:"+CacheManager.getCacheInfo("one"<span style="color: rgba(0, 0, 0, 1)">).getValue());
    
    
    System.out.println(</span>"-----------------------------------"<span style="color: rgba(0, 0, 0, 1)">);
    
    
    </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">Demo2</span>
    Cache c3 = <span style="color: rgba(0, 0, 255, 1)">new</span><span style="color: rgba(0, 0, 0, 1)"> Cache();
    c3.setKey(</span>"小客车品牌列表"<span style="color: rgba(0, 0, 0, 1)">);
    
    List</span>&lt;String&gt; list1 = <span style="color: rgba(0, 0, 255, 1)">new</span> ArrayList&lt;String&gt;<span style="color: rgba(0, 0, 0, 1)">();
    list1.add(</span>"奔驰"<span style="color: rgba(0, 0, 0, 1)">);
    list1.add(</span>"宝马"<span style="color: rgba(0, 0, 0, 1)">);
    list1.add(</span>"奥迪"<span style="color: rgba(0, 0, 0, 1)">);
    list1.add(</span>"现代"<span style="color: rgba(0, 0, 0, 1)">);
    
    c3.setValue(list1);
    
    CacheManager.putCache(</span>"car"<span style="color: rgba(0, 0, 0, 1)">, c3);
    List</span>&lt;String&gt; list2 = <span style="color: rgba(0, 0, 255, 1)">new</span> ArrayList&lt;String&gt;<span style="color: rgba(0, 0, 0, 1)">();
    Object obCar </span>= CacheManager.getCacheInfo("car"<span style="color: rgba(0, 0, 0, 1)">).getValue();
    </span><span style="color: rgba(0, 0, 255, 1)">if</span>(obCar <span style="color: rgba(0, 0, 255, 1)">instanceof</span><span style="color: rgba(0, 0, 0, 1)"> List){
        list2 </span>= (List&lt;String&gt;<span style="color: rgba(0, 0, 0, 1)">) obCar;
    }
    </span><span style="color: rgba(0, 0, 255, 1)">for</span><span style="color: rgba(0, 0, 0, 1)">(String brand : list2){
        System.out.println(</span>"Key为car的品牌:"+<span style="color: rgba(0, 0, 0, 1)">brand);
    }
    
    
    System.out.println(</span>"-----------------------------------"<span style="color: rgba(0, 0, 0, 1)">);
    
    
    </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">Demo3</span>
    Cache c4 = <span style="color: rgba(0, 0, 255, 1)">new</span><span style="color: rgba(0, 0, 0, 1)"> Cache();
    c4.setKey(</span>"朗行-自动1.8T"<span style="color: rgba(0, 0, 0, 1)">);
    
    Cache c5 </span>= <span style="color: rgba(0, 0, 255, 1)">new</span><span style="color: rgba(0, 0, 0, 1)"> Cache();
    c5.setKey(</span>"朗境-双离合2.0T"<span style="color: rgba(0, 0, 0, 1)">);
    
    Cache c6 </span>= <span style="color: rgba(0, 0, 255, 1)">new</span><span style="color: rgba(0, 0, 0, 1)"> Cache();
    c6.setKey(</span>"夏朗-自动1.8T"<span style="color: rgba(0, 0, 0, 1)">);
    
    Cache c7 </span>= <span style="color: rgba(0, 0, 255, 1)">new</span><span style="color: rgba(0, 0, 0, 1)"> Cache();
    c7.setKey(</span>"朗逸-双离合2.0T"<span style="color: rgba(0, 0, 0, 1)">);
    
    Cache c8 </span>= <span style="color: rgba(0, 0, 255, 1)">new</span><span style="color: rgba(0, 0, 0, 1)"> Cache();
    c8.setKey(</span>"速腾-自动1.8T"<span style="color: rgba(0, 0, 0, 1)">);

    Cache c9 </span>= <span style="color: rgba(0, 0, 255, 1)">new</span><span style="color: rgba(0, 0, 0, 1)"> Cache();
    c9.setKey(</span>"迈腾-双离合2.0T"<span style="color: rgba(0, 0, 0, 1)">);

    Cache c10 </span>= <span style="color: rgba(0, 0, 255, 1)">new</span><span style="color: rgba(0, 0, 0, 1)"> Cache();
    c10.setKey(</span>"辉腾-双离合2.0T"<span style="color: rgba(0, 0, 0, 1)">);
    Map</span>&lt;String,String&gt; map1 = <span style="color: rgba(0, 0, 255, 1)">new</span> HashMap&lt;String,String&gt;<span style="color: rgba(0, 0, 0, 1)">();
    map1.put(</span>"全景天窗", "是"<span style="color: rgba(0, 0, 0, 1)">);
    map1.put(</span>"发动机排量", "2.0L"<span style="color: rgba(0, 0, 0, 1)">);
    map1.put(</span>"排放标准", "国5"<span style="color: rgba(0, 0, 0, 1)">);
    c10.setValue(map1);

    Cache c11 </span>= <span style="color: rgba(0, 0, 255, 1)">new</span><span style="color: rgba(0, 0, 0, 1)"> Cache();
    c11.setKey(</span>"英菲尼迪-1.8T都市精英版"<span style="color: rgba(0, 0, 0, 1)">);
    
    CacheManager.putCache(</span>"朗行"<span style="color: rgba(0, 0, 0, 1)">, c4);
    CacheManager.putCache(</span>"朗境"<span style="color: rgba(0, 0, 0, 1)">, c5);
    CacheManager.putCache(</span>"朗逸"<span style="color: rgba(0, 0, 0, 1)">, c6);
    CacheManager.putCache(</span>"夏朗"<span style="color: rgba(0, 0, 0, 1)">, c7);
    CacheManager.putCache(</span>"速腾"<span style="color: rgba(0, 0, 0, 1)">, c8);
    CacheManager.putCache(</span>"迈腾"<span style="color: rgba(0, 0, 0, 1)">, c9);
    CacheManager.putCache(</span>"辉腾"<span style="color: rgba(0, 0, 0, 1)">, c10);
    
    </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">得到朗系家族的车产品</span>
    Object carObj2 = CacheManager.getCacheListLikekey("朗"<span style="color: rgba(0, 0, 0, 1)">);
    List</span>&lt;String&gt; list3 = <span style="color: rgba(0, 0, 255, 1)">new</span> ArrayList&lt;String&gt;<span style="color: rgba(0, 0, 0, 1)">();
    </span><span style="color: rgba(0, 0, 255, 1)">if</span>(carObj2 <span style="color: rgba(0, 0, 255, 1)">instanceof</span><span style="color: rgba(0, 0, 0, 1)"> List){
        list3 </span>= (List&lt;String&gt;<span style="color: rgba(0, 0, 0, 1)">) carObj2;
    }
    </span><span style="color: rgba(0, 0, 255, 1)">for</span><span style="color: rgba(0, 0, 0, 1)">(String product : list3){
        System.out.println(</span>"朗系家族:"+<span style="color: rgba(0, 0, 0, 1)">product);
    }

    System.out.println(</span>"-----------------------------------"<span style="color: rgba(0, 0, 0, 1)">);
    
    </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">得到X腾系列的车产品</span>
    Object carObj3 = CacheManager.getCacheListLikekey("腾"<span style="color: rgba(0, 0, 0, 1)">);
    List</span>&lt;String&gt; list4 = <span style="color: rgba(0, 0, 255, 1)">new</span> ArrayList&lt;String&gt;<span style="color: rgba(0, 0, 0, 1)">();
    </span><span style="color: rgba(0, 0, 255, 1)">if</span>(carObj2 <span style="color: rgba(0, 0, 255, 1)">instanceof</span><span style="color: rgba(0, 0, 0, 1)"> List){
        list4 </span>= (List&lt;String&gt;<span style="color: rgba(0, 0, 0, 1)">) carObj3;
    }
    </span><span style="color: rgba(0, 0, 255, 1)">for</span><span style="color: rgba(0, 0, 0, 1)">(String product : list4){
        System.out.println(</span>"腾系家族:"+<span style="color: rgba(0, 0, 0, 1)">product);
    }
    
    System.out.println(</span>"-----------------------------------"<span style="color: rgba(0, 0, 0, 1)">);
    System.out.println(</span>"此时的缓存大小:"+<span style="color: rgba(0, 0, 0, 1)">CacheManager.getCacheSize());
    
}</span></pre>