TA的每日心情 | 开心 2021-3-12 23:18 |
---|
签到天数: 2 天 [LV.1]初来乍到
|
对于一些全局性的统计信息,不能每次使用都重新取一遍数据,按照次数或者时间缓存一段时间是比较好的方案,既达到了一定的实时性又提高了系统的整体性能。下面的两个类合作可以完成这种缓存功能的处理,需要缓存的内容实现类需要实现ShortTimeCachable,在reset方法中完成数据的读取操作。
/**
* Copyright: Copyright (c) 2005-2005
* Company: javaresearch( http://www.javaresearch.org/ )
* 最后更新日期:2005-2-15
* @author Cherami
*/
package org.javaresearch.core;
/**
* 时间/次数双机制可缓存接口定义。
*/
public interface ShortTimeCachable {
//缓存时效到了以后刷新缓存内容的接口方法。
public void reset();
}
/**
* Copyright: Copyright (c) 2005-2005
* Company: Javaresearch( http://www.javaresearch.org/ )
* 创建日期:2005-2-15
* 最后更新日期:2005-2-15
* @author Cherami
*/
package org.javaresearch.core;
import java.util. HashMap ;
/**
* 时间/次数双机制缓存管理器。
* 如果只想使用其中的一种机制,将另外的一种机制的值设置为小于等于0的值即可。
*/
public class ShortTimeCacheManager {
private static HashMap caches = new HashMap ();
private static ShortTimeCacheManager instance = new ShortTimeCacheManager();
/**
* 创建新的缓存项并且初始化缓存内容。
* @param keepCount 缓存次数
* @param keepSeconds 缓存秒数
* @param cacheObject 缓存实例对象
*/
public static void addCache( int keepCount, int keepSeconds,
ShortTimeCachable cacheObject) {
caches.put(cacheObject, instance.createNewCache(keepCount, keepSeconds));
cacheObject.reset();
}
/**
* 创建新的Cache内部类。
* @param keepCount 缓存次数
* @param keepSeconds 缓存秒数
* @return
*/
Cache createNewCache( int keepCount, int keepSeconds) {
return new Cache(keepCount, keepSeconds);
}
/**
* 使用一次缓存中的内容。
* 如果缓存次数或者时间到了将刷新缓存内容。
* 如果管理器中不存在对应的对象则不做任何事情。
* @param cacheObject 缓存实例对象
*/
public static void touch(ShortTimeCachable cacheObject) {
Cache cache = (Cache) caches.get(cacheObject);
if (cache != null ) {
cache.cachedCount++;
if (cache.needFresh()) {
cacheObject.reset();
cache.reset();
}
}
}
/**
* 缓存信息内部类。
*/
class Cache {
int cachedCount; //已经缓存的次数
long lastCacheTime; //上次缓存时间
int cacheCount; //缓存次数
long cacheTime; //缓存时间
public Cache( int cacheCount, int cacheSeconds) {
this .cacheCount = cacheCount;
this .cacheTime = cacheSeconds * 1000;
reset();
}
/**
* 重置已经缓存的次数和上次缓存时间。
*/
void reset() {
cachedCount = 0;
lastCacheTime = System .currentTimeMillis();
}
/**
* 缓存是否需要刷新。
* @return 如果缓存次数大于0并且已经缓存的次数大于等于缓存次数返回true,
* 如果缓存时间大于0并且当前时间大于等于上次缓存的时间加上缓存时间则返回true,
* 否则返回false。
*/
boolean needFresh() {
if (cacheCount > 0 && cachedCount >= cacheCount) {
return true ;
}
if (cacheTime > 0
&& System .currentTimeMillis() >= lastCacheTime + cacheTime) {
return true ;
}
return false ;
}
}
} |
|