public class WebContextCache
{
/** 写日志 */
private static Log logger = LogFactory.getLog(WebContextCache.class);
private static WebContextCache instance = new WebContextCache();
/**
* 初始化缓存大小
*/
private static final int CAPACITY_NUM = 200;
private Map<String, ApplicationSession> applicationMap = new ConcurrentHashMap<String, ApplicationSession>(
CAPACITY_NUM);
public static WebContextCache getInstance()
{
return instance;
}
public static void createAppSession(String id, ApplicationSession appSession)
{
getInstance().applicationMap.put(id, appSession);
if (!getInstance().applicationMap.containsKey(id))
{
logger.info(id + ":cache init failure");
}
}
public static void remoteAppSession(String id)
{
ApplicationSession appSession = getInstance().applicationMap.remove(id);
if (appSession != null)
{
appSession.clearApplicationSession();
}
}
public static ApplicationSession getAppSession(String id)
{
ApplicationSession appSession = getInstance().applicationMap.get(id);
if (appSession == null)
{
logger.info(id + ":cache space has not been inited or been removed");
appSession = new ApplicationSession();
WebContextCache.createAppSession(id, appSession);
}
return appSession;
}
}
Java代码
public class ApplicationSession
{
/**
* 默认的map初始化大小
*/
private static final int DEFAULT_MAP_SIZE = 100;
private final Map cache = new HashMap(DEFAULT_MAP_SIZE);
public Object getFromCache(Object key)
{
synchronized (cache)
{
return cache.get(key);
}
}
public void putToCache(Object key, Object value)
{
synchronized (cache)
{
cache.put(key, value);
}
}
public void removeAllCache()
{
synchronized (cache)
{
cache.clear();
}
}
public void clearApplicationSession()
{
cache.clear();
}
}
Java代码
public abstract class ActionSupport extends Action
{
protected void putToCache(HttpServletRequest request, Object key, Object value)
{
ApplicationSession appSession = WebContextCache.getAppSession(request.getSession(true)
.getId());
appSession.putToCache(key, value);
}
protected Object getObjectFromCache(HttpServletRequest request, Object key)
{
ApplicationSession appSession = WebContextCache.getAppSession(request.getSession(true)
.getId());
return appSession.getFromCache(key);
}
}
java缓存
最新推荐文章于 2024-09-22 15:00:00 发布