基于Redis实现分布式Session(二)

2015-07-16 12:08:31 · 作者: · 浏览: 4
trName);
? ? ? ? CacheBlock cb = CacheManager.getBlock(Const.CACHE_BLOCK_INDEX);
? ? ? ? CacheElement ce = new CacheElement(attrSessionKey,attrValue);
? ? ? ? ce.setTimeToIdleSeconds(this.getMaxInactiveInterval());
? ? ? ? cb.put(ce);
? ? }


? ? /**
? ? * 获取属性的值。
? ? * @param attrName
? ? * @return
? ? */
? ? public Object getAttribute(String attrName){
? ? ? ? this.refresh();
? ? ? ? String attrSessionKey = getAttrSessionKey(attrName);
? ? ? ? CacheBlock cb = CacheManager.getBlock(Const.CACHE_BLOCK_INDEX);
? ? ? ? Object retObject = cb.get(attrSessionKey);
? ? ? ? return retObject;
? ? }


? ? private String getAttrSessionKey(String attrName){
? ? ? ? String attrSessionKey = sessionKey + attrName;
? ? ? ? return attrSessionKey;
? ? }


? ? public int getMaxInactiveInterval() {
? ? ? ? if(maxInactiveInterval==-1){
? ? ? ? ? ? maxInactiveInterval = 3600;
? ? ? ? }
? ? ? ? return maxInactiveInterval;
? ? }


? ? public void setMaxInactiveInterval(int maxInactiveInterval) {
? ? ? ? this.maxInactiveInterval = maxInactiveInterval;
? ? }


? ? public String getId() {
? ? ? ? return id;
? ? }


? ? public long getCreationTime() {
? ? ? ? return creationTime;
? ? }


? ? public long getLastAccessedTime() {
? ? ? ? return lastAccessedTime;
? ? }


? ? public boolean isNewSession() {
? ? ? ? return newSession;
? ? }
}


3、用法
3.1、建立Session
// 建立Session
int maxIdleSeconds = 60 * 20 ;
ApiSession session = new ApiSession( maxIdleSeconds );
String sessId = session.getId();
session.setAttribute("CURRENT_USER", user);1
3.2、读取Session
// 读取Session
ApiSession session = ApiSession.get(tokenToBeChecked);
if(session==null){
? ? logger.debug(String.format("会话超时啦,token:%s。", tokenToBeChecked));
? ? return false;
}
// 检查是否超时
boolean isExpired = session.isExpired();
if(isExpired){
? ? logger.debug(String.format("会话超时啦,token:%s。", tokenToBeChecked));
? ? return false;
}
// 从Sesion中取出token
String token = (String)session.getAttribute(Const.TOKEN_SESSION_KEY);
if(StringUtils.isEmpty(token)){
? ? return false;
}
// 同调用方提交的比较
if(token.equalsIgnoreCase(tokenToBeChecked)){
? ? session.refresh();
? ? return true;
}


4、优化点
以上只是提供了实现范例。进一步的优化点包括:


Redis存储规划,设计Session Id 、Attr的存储方式。
采用自己的持久化方式,提高持久化效率。
提供更多工具方法,让Session更易用。
进一步实现Session的其他接口。
等等。


未尽事宜,欢迎留言讨论。