/**
|
*
|
*/
|
package com.vci.server.framework.Logon;
|
|
import java.util.Timer;
|
import java.util.TimerTask;
|
import java.util.concurrent.ConcurrentHashMap;
|
|
import com.vci.corba.framework.data.UserInfo;
|
|
/**
|
* @author Jason
|
* 登录信息Session管理
|
*/
|
public class LogonSessionManager {
|
|
/**
|
* 缓存Map对象
|
*/
|
private static ConcurrentHashMap<String, LogonSession> mapSession = new ConcurrentHashMap<String, LogonSession>();
|
|
/**
|
* 登录失效时间,默认为3分钟
|
*/
|
private static long _timeExpire = 3 * 60 * 1000;
|
|
/**
|
* 创建定时任务每分钟清理一次缓存
|
*/
|
static{
|
Timer timer = new Timer();
|
timer.schedule(new TimerTask() {
|
@Override
|
public void run() {
|
refresh();
|
}
|
},0,60000);
|
}
|
|
/**
|
* 缓存刷新,清除过期数据
|
*/
|
public static void refresh(){
|
for (String key : mapSession.keySet()) {
|
if(isExpire(key)){
|
remove(key);
|
}
|
}
|
}
|
|
/**
|
* 加入缓存
|
* @param key
|
* @param value
|
*/
|
public static boolean put(String token, UserInfo user){
|
if(token.isEmpty()){
|
return false;
|
}
|
LogonSession session = new LogonSession(user);
|
mapSession.put(token, session);
|
return true;
|
}
|
|
/**
|
* 移除缓存数据
|
* @param key
|
*/
|
public static boolean remove(String token){
|
if(token.isEmpty()){
|
return false;
|
}
|
if(!mapSession.containsKey(token)){
|
return true;
|
}
|
mapSession.remove(token);
|
return true;
|
}
|
|
/**
|
* 获取缓存数据
|
* @param key
|
* @return
|
*/
|
public static Object get(String key){
|
if(key.isEmpty()||isExpire(key)){
|
return null;
|
}
|
LogonSession cacheEntity = mapSession.get(key);
|
if(null == cacheEntity){
|
return null;
|
}
|
return cacheEntity.getValue();
|
}
|
|
/**
|
* 判断当前数据是否已过期
|
* @param key
|
* @return
|
*/
|
private static boolean isExpire(String token){
|
if(token.isEmpty()){
|
return false;
|
}
|
if(mapSession.containsKey(token)){
|
LogonSession cacheEntity = mapSession.get(token);
|
long currentTime = System.currentTimeMillis();
|
long accTime = cacheEntity.getAccessTime();
|
if ((currentTime - accTime) > _timeExpire){
|
return true;
|
}
|
return false;
|
}
|
return false;
|
}
|
|
/**
|
* 获取当前缓存大小(包含已过期但未清理的数据)
|
* @return
|
*/
|
public static int getCacheSize(){
|
return mapSession.size();
|
}
|
}
|