Sparkle’s Workshop

一个很简单的缓存

Posted on September 28, 2005 - Filed Under Uncategorized |

使用方法

bbs_topic=0s
RandomUserId=5s
newCouple=10m
DMSCategory=30m
count=30m
hot_club=1h
new_club=30m
province=1d
pet=10m
album=2m
dms=30m
dmsDownloadHot=30m

// read from cache
String key = catalogId;
Object obj = WcpCacheManager.get(”DMSCategory”, key);
if (obj != null) {
return (List) obj;
}
//read from db code
//xx yy zz
// put into cache
WcpCacheManager.set(”DMSCategory”, key, list);
return list;

实现
public class WcpCacheManager {
private static Log log = LogFactory.getLog(WcpCacheManager.class);

private static Map cacheMap = new HashMap();
static {
InputStream is = null;
try {
Properties props = new Properties();
is = Thread.currentThread().getContextClassLoader()
.getResourceAsStream(”cache.properties”);
props.load(is);

for (Object obj : props.keySet()) {
try {
String key = (String) obj;
String str = props.getProperty(key);

int radio = 1;
char endChar = str.charAt(str.length() - 1);
switch (endChar) {
case ‘d’:
radio *= 24;
case ‘h’:
radio *= 60;
case ‘m’:
radio *= 60;
case ’s’:
str = str.substring(0, str.length() - 1);
break;
default:
break;
}

long second = Long.parseLong(str) * radio;
cacheMap.put(key, new WcpCache(second));
} catch (NumberFormatException e1) {
}
}
} catch (IOException e) {
log.error(”load cache.properties error”, e);
} finally {
try {
is.close();
} catch (IOException e) {
}
}
}

public static Object get(String cacheName, String key) {
WcpCache cache = cacheMap.get(cacheName);
return cache == null ? null : cache.getContent(key);
}

public static void set(String cacheName, String key, Object content) {
WcpCache cache = cacheMap.get(cacheName);
if (cache != null) {
cache.setContent(key, content);
}
}
}

public class WcpCache {
private long liveMillis;

public WcpCache(long liveSecond) {
this.liveMillis = liveSecond * 1000;
}

private Map contentMap = new HashMap();

private Map timestampMap = new HashMap();

public void setContent(String key, Object content) {
if (liveMillis <= 0) {
return;
}
if (content == null) {
timestampMap.remove(key);
contentMap.remove(key);
return;
}
timestampMap.put(key, System.currentTimeMillis());
contentMap.put(key, content);
}

public Object getContent(String key) {
if (liveMillis <= 0) {
return null;
}
if (!timestampMap.containsKey(key)) {
return null;
}
if (!contentMap.containsKey(key)) {
return null;
}
if (timestampMap.get(key) + liveMillis < System.currentTimeMillis()) {
contentMap.remove(key);
return null;
}
return contentMap.get(key);
}
}

Most Commented Posts

Comments

Leave a Reply