本地缓存
1、工具类实现本地缓存
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class LocalCache implements Comparable<LocalCache> {
private Object key;
private Object value;
private long lastAccessTime;
private long createTime;
private long expireTime;
private Integer hitCount;
@Override
public int compareTo(LocalCache o) {
return hitCount.compareTo(o.hitCount);
}
}
import java.util.Collections;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import com.alibaba.fastjson.JSONObject;
import com.hihonor.truss.core.core.log.TrussLoggerFactory;
public class LocalCacheUtil<K, V> {
public static Logger LOGGER = TrussLoggerFactory.getLogger(LocalCacheUtil.class);
private ConcurrentHashMap<Object, LocalCache> concurrentHashMap;
final int size;
public LocalCacheUtil(int capacity) {
this.size = capacity;
this.concurrentHashMap = new ConcurrentHashMap<>(capacity);
new Thread(new TimeoutTimerThread()).start();
}
public Object get(K key) {
if (concurrentHashMap.isEmpty()) {
return null;
}
if (!concurrentHashMap.containsKey(key)) {
return null;
}
LocalCache cache = concurrentHashMap.get(key);
if (cache == null) {
return null;
}
cache.setHitCount(cache.getHitCount() + 1);
cache.setLastAccessTime(System.currentTimeMillis());
return cache.getValue();
}
public void put(K key, V value, long expire) {
if (concurrentHashMap.containsKey(key)) {
LocalCache cache = concurrentHashMap.get(key);
cache.setHitCount(cache.getHitCount() + 1);
cache.setCreateTime(System.currentTimeMillis());
cache.setLastAccessTime(System.currentTimeMillis());
cache.setExpireTime(expire * 1000 * 1000 * 1000);
cache.setValue(value);
return;
}
if (isFull()) {
Object kickedKey = getKickedKey();
if (kickedKey != null) {
concurrentHashMap.remove(kickedKey);
} else {
return;
}
}
LocalCache cache = new LocalCache();
cache.setKey(key);
cache.setValue(value);
cache.setCreateTime(System.currentTimeMillis());
cache.setLastAccessTime(System.currentTimeMillis());
cache.setHitCount(1);
cache.setExpireTime(expire * 1000 * 1000 * 1000);
concurrentHashMap.put(key, cache);
}
public void queryCache() {
if (concurrentHashMap.isEmpty()) {
LOGGER.info("Cache is empty");
return;
}
Iterator<Map.Entry<Object, LocalCache>> entries = concurrentHashMap.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry<Object, LocalCache> entry = entries.next();
LocalCache value = entry.getValue();
String localCacheJson = JSONObject.toJSONString(value);
System.out.println("Key = " + entry.getKey() + ", Value = " + localCacheJson + "\n");
}
}
private boolean isFull() {
return concurrentHashMap.size() == size;
}
private Object getKickedKey() {
LocalCache min = Collections.min(concurrentHashMap.values());
return min.getKey();
}
class TimeoutTimerThread implements Runnable {
public void run() {
while (true) {
try {
TimeUnit.SECONDS.sleep(60);
expireCache();
} catch (Exception e) {
e.printStackTrace();
}
}
}
private void expireCache() throws Exception {
LOGGER.info("Check whether the cache is out of date");
for (Object key : concurrentHashMap.keySet()) {
LocalCache cache = concurrentHashMap.get(key);
long timoutTime = TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - cache.getCreateTime());
if (cache.getExpireTime() > timoutTime) {
continue;
}
LOGGER.info("Clear expired cache key:{}", key);
concurrentHashMap.remove(key);
}
}
}
}
2、实现简单的Map缓存
private static final ConcurrentHashMap<String, LocalCache> localCache = new ConcurrentHashMap<>(100);
public void createOrUpdateLocalCache(String key, Credentials value, long expire) {
if (localCache.containsKey(key)) {
LocalCache cache = localCache.get(key);
cache.setHitCount(cache.getHitCount() + 1);
cache.setCreateTime(System.currentTimeMillis());
cache.setLastAccessTime(System.currentTimeMillis());
cache.setExpireTime(expire * 1000 * 1000 * 1000);
cache.setValue(value);
return;
}
LocalCache cache = new LocalCache();
cache.setKey(key);
cache.setValue(value);
cache.setCreateTime(System.currentTimeMillis());
cache.setLastAccessTime(System.currentTimeMillis());
cache.setHitCount(1);
cache.setExpireTime(expire * 1000 * 1000 * 1000);
localCache.put(key, cache);
}
public Object getLocalCache(String key) {
LocalCache cache = localCache.get(key);
cache.setHitCount(cache.getHitCount() + 1);
cache.setLastAccessTime(System.currentTimeMillis());
return cache.getValue();
}
public void queryCache() {
if (localCache.isEmpty()) {
LOGGER.info("Cache is empty");
return;
}
for (Map.Entry<String, LocalCache> entry : localCache.entrySet()) {
LocalCache value = entry.getValue();
String localCacheJson = JSONObject.toJSONString(value);
System.out.println("Key = " + entry.getKey() + ", Value = " + localCacheJson + "\n");
}
}
3、极其简单本地缓存
private static final ConcurrentHashMap<String, Credentials> credentialsLocalCache = new ConcurrentHashMap<>(16);
Credentials alternateCredential = credentialsLocalCache.get(key);
credentialsLocalCache.put(key, alternateCredentials);