1.CommomLocalCache
import org.springframework.stereotype.Component;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
/**
* 公用本地缓存
*/
@Component
public class CommomLocalCache implements LocalCache{
private static ConcurrentHashMap<String, LocalCacheItem> cache = new ConcurrentHashMap<>();
public static boolean containsKey(String key){
return cache.containsKey(key);
}
/**
* 缓存值
* @author:
* @param key
* @param value
*/
public static void put(String key, Object value){
LocalCacheItem item = new LocalCacheItem(0, System.currentTimeMillis(), value);
cache.put(key, item);
}
/**
* 缓存值-指定缓存时间
* @author:
* @param key
* @param value
* @param cacheTime 缓存时间
* @param unit 缓存时间单位
*/
public static void put(String key, Object value, long cacheTime, TimeUnit unit){
LocalCacheItem item = new LocalCacheItem(unit.toMillis(cacheTime), System.currentTimeMillis(), value);
cache.put(key, item);
}
/**
* 获取值
* @author:
* @param key
* @return
*/
@SuppressWarnings("unchecked")
public static <T>T get(String key){
LocalCacheItem item = cache.get(key);
if(item==null){
return null;
}
return (T)item.getValue();
}
@Override
public void refresh() {
for(String key : cache.keySet()){
LocalCacheItem item = cache.get(key);
//过期了移除缓存
long currentTime = System.currentTimeMillis();
if(item.getCacheTime()>0 && currentTime - item.getCreateTime() > item.getCacheTime()) {
cache.remove(key);
}
}
}
}
2.LocalCache
public interface LocalCache {
void refresh();
}
3.LocalCacheItem
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* 缓存项
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class LocalCacheItem {
//缓存时间:单位毫秒
private long cacheTime;
//创建时间:单位毫秒
private long createTime;
//缓存值
private Object value;
}
4.LocalCacheManage
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
/**
* 本地缓存管理器,CommandLineRunner应用启动执行
*/
@Component
public class LocalCacheManage implements CommandLineRunner{
@Autowired private List<LocalCache> localCaches;
private Logger logger = LoggerFactory.getLogger(this.getClass());
/**
* 应用启动初始化
*/
@Override
public void run(String... args) throws Exception {
// 1分钟刷新一次,时间可以自定义。这里作为心跳线程,定时1分钟刷新缓存
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
if(localCaches!=null && !localCaches.isEmpty()){
for(LocalCache cache : localCaches){
try {
cache.refresh();
} catch (Exception e) {
logger.error("本地缓存更新异常", e);
}
}
}
}
}, 0, 60000);
}
}