您的位置:首页 > 其它

一般cache的做法

2015-05-26 10:47 211 查看
其实比较简单,直接来个例子,e.g.

TryCache.java

public class InforoneCache<K, V> implements Cache<K, V> {

class CacheObject<K2, V2> {
final K2 key;
final V2 value;
long lastModified; // 最后添加时间
long expire; // 对象存活时间

CacheObject(K2 key, V2 value, long expire) {
this.key = key;
this.value = value;
this.lastModified = System.currentTimeMillis();
this.expire = expire;
}

boolean isExpired() {
if (expire == 0) {
return false;
}
return lastModified + expire < System.currentTimeMillis();
}

V2 getObject() {
return value;
}
}

protected Map<K, CacheObject<K, V>> cacheMap;

private final ReentrantReadWriteLock cacheLock = new ReentrantReadWriteLock();
private final Lock readLock = cacheLock.readLock();
private final Lock writeLock = cacheLock.writeLock();

protected int cacheSize; // 缓存大小 , 0 -> 无限制

protected boolean existCustomExpire; // 是否设置默认过期时间

public int getCacheSize() {
return cacheSize;
}

protected long defaultExpire; // 默认过期时间, 0 -> 永不过期

public TryCache(int cacheSize, long defaultExpire) {
this.cacheSize = cacheSize;
this.defaultExpire = defaultExpire;
cacheMap = new HashMap<K, CacheObject<K, V>>(cacheSize + 1);
}

public long getDefaultExpire() {
return defaultExpire;
}

public void put(K key, V value) {
put(key, value, defaultExpire);
}

public void put(K key, V value, long expire) {
writeLock.lock();

try {
CacheObject<K, V> co = new CacheObject<K, V>(key, value, expire);
if (expire != 0) {
existCustomExpire = true;
}
cacheMap.put(key, co);
} finally {
writeLock.unlock();
}
}

/**
* {@inheritDoc}
*/
public V get(K key) {
readLock.lock();

try {
CacheObject<K, V> co = cacheMap.get(key);
if (co == null) {
return null;
}
if (co.isExpired() == true) {
cacheMap.remove(key);
return null;
}

return co.getObject();
} finally {
readLock.unlock();
}
}

public boolean isFull() {
if (cacheSize == 0) {// o -> 无限制
return false;
}
return cacheMap.size() >= cacheSize;
}

public void remove(K key) {
writeLock.lock();
try {
cacheMap.remove(key);
} finally {
writeLock.unlock();
}
}

public void clear() {
writeLock.lock();
try {
cacheMap.clear();
} finally {
writeLock.unlock();
}
}

public int size() {
return cacheMap.size();
}

public boolean isEmpty() {
return size() == 0;
}

}


GetData.java

static final InforoneCache<String, DatumMining> cache = new InforoneCache<String, DatumMining>(0, 30 * 60 * 1000L);
public getData() {
Xxx xxx = cache.get(key);
if (DatumMining == null) {
...
}
cache.put(key, xxx);
}


跨节点情况请参考:一致性hash算法: cache、负载均衡应用
http://blog.csdn.net/textboy/article/details/46004117
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: