java缓存

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);
}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值