简单实现本地缓存

package cn.zyx;

import java.io.Serializable;

public class CacheEntity implements Serializable{

private static final long serialVersionUID = -4653471779730170360L;

/**
 * 值
 */
private Object value;
/**
 * 时间戳
 */
private long timestamp;

/**
 * 过期时间
 */
private int expire;

public Object getValue() {
    return value;
}

public void setValue(Object value) {
    this.value = value;
}

public long getTimestamp() {
    return timestamp;
}

public void setTimestamp(long timestamp) {
    this.timestamp = timestamp;
}

public int getExpire() {
    return expire;
}

public void setExpire(int expire) {
    this.expire = expire;
}


public CacheEntity(Object value , long timestamp , int expire){
    super(); 
    this.value = value;
    this.timestamp = timestamp;
    this.expire = expire;
}

}

/**
* 简易的本地缓存实现类
*
* @author Administrator
*
*/
public class LocalCache {
// 默认的缓存容量
private static int DEFAULT_CAPACITY = 512;
// 做大的缓存容量
private static int MAX_CAPACITY = 100000;
// 刷新缓存的频率
private static int MONITOR_DERATION = 2;

static {
    new Thread(new TimeoutTimerThread()).start();
}

private static ConcurrentHashMap<String, CacheEntity> cache = new ConcurrentHashMap<String, CacheEntity>(
        DEFAULT_CAPACITY);

/**
 * 将值通过序列化clone 处理后保存到缓存中,可以解决值引用的问题
 * 
 * @param key
 * @param value
 * @param expire
 * @return
 */
public boolean putKey(String key, Object value, int expire) {
    return putCloneValue(key, value, expire);
}



/**
 * 将值通过序列化clone 处理后保存到缓存中,可以解决值引用的问题
 * 
 * @param key
 * @param value
 * @param timestamp
 * @param expire
 * @return
 */
private boolean putCloneValue(String key, Object value, int expire) {
    if (cache.size() > MAX_CAPACITY) {
        return false;
    }
    CacheEntity cacheEntity = clone(new CacheEntity(value,
            System.nanoTime(), expire));
    cache.put(key, cacheEntity);

    return true;
}

/**
 * 
 * 序列化 克隆处理
 * 
 * @param object
 * @return
 */
private <T extends Serializable> T clone(T object) {
    T cloneObject = null;
    try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(baos);
        oos.writeObject(object);
        oos.close();
        ByteArrayInputStream bais = new ByteArrayInputStream(
                baos.toByteArray());
        ObjectInputStream ois = new ObjectInputStream(bais);
        cloneObject = (T) ois.readObject();
        ois.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return cloneObject;
}

/**
 * 从本地缓存中获取key对应的值,如果该值不存则则返回null
 * 
 * @param key
 * @return
 */
public Object getValue(String key) {
    return cache.get(key).getValue();
}

/**
 * 清空所有
 */
public void clear() {
    cache.clear();
}

/**
 * 过期处理线程
 * 
 * @author Administrator
 * 
 */
static class TimeoutTimerThread implements Runnable {
    public void run() {
        while (true) {
            try {
                System.out.println("Cache monitor");
                TimeUnit.SECONDS.sleep(MONITOR_DERATION);
                checkTime();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

/**
 * 过期缓存的具体处理方法
 */
private static void checkTime() {
    for (String key : cache.keySet()) {
        CacheEntity cacheEntity = cache.get(key);
        long timeout = TimeUnit.NANOSECONDS.toSeconds(System.nanoTime()
                - cacheEntity.getTimestamp());
        if (cacheEntity.getExpire() > timeout) {
            continue;
        }
        System.out.println(" 清除过期缓存 : " + key);
        // 清除过期缓存和删除对应的缓存队列
        cache.remove(key);
    }
}

}

package cn.zyx;

public class TestCache {
public static void main(String []args){
LocalCache cache = new LocalCache();
cache.putKey(“name”, “zyx”, 0);
System.out.println(“name:”+cache.getValue(“name”));
cache.clear();
System.out.println(“name:”+cache.getValue(“name”));

}

}

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值