一般cache的做法

来源:互联网 发布:淘宝上怎么购买电棍 编辑:程序博客网 时间:2024/04/28 05:47

其实比较简单,直接来个例子,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

0 0
原创粉丝点击