Tomcat中session详解(源码阅读)
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Tomcat中session详解(源码阅读),小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含6293字,纯文字阅读大概需要9分钟。
内容图文
![Tomcat中session详解(源码阅读)](/upload/InfoBanner/zyjiaocheng/1185/6f59327b3e7f460ebca7f3f18c428af8.jpg)
Tomcat中的session是通过一个manager来管理的,其中Session接口默认实现类有StandardSession,管理器的默认实现是StandardManager。
我们平时在servlet中使用的session也就是HashMap中的一个session对象,同时session除了在内存存储,同时还提供了持久化方法,tomcat中持久化有两种,一种是保存为文件,另一种则是保存到数据库。
这一节首先来看一下默认的StandardSession和StandardManager。
public
interface
Session {
// ----------------------------------------------------- Manifest Constants
public
static
final String SESSION_CREATED_EVENT = "createSession";
publicstaticfinal String SESSION_DESTROYED_EVENT = "destroySession";
// ------------------------------------------------------------- Propertiespublic String getAuthType();
publicvoidsetAuthType(String authType);
publiclonggetCreationTime();
publicvoidsetCreationTime(long time);
public String getId();
publicvoidsetId(String id);
public String getInfo();
publiclonggetLastAccessedTime();
public Manager getManager();
publicvoidsetManager(Manager manager);
publicintgetMaxInactiveInterval();
publicvoidsetMaxInactiveInterval(int interval);
publicvoidsetNew(boolean isNew);
public Principal getPrincipal();
publicvoidsetPrincipal(Principal principal);
public HttpSession getSession();
publicvoidsetValid(boolean isValid);
publicbooleanisValid();
// --------------------------------------------------------- Public Methodspublicvoidaccess();
publicvoidaddSessionListener(SessionListener listener);
publicvoidexpire();
public Object getNote(String name);
public Iterator getNoteNames();
publicvoidrecycle();
publicvoidremoveNote(String name);
publicvoidremoveSessionListener(SessionListener listener);
publicvoidsetNote(String name, Object value);
}
1.StandardManager中整个启动过程
public
void
start() throws LifecycleException {
if (debug >= 1)
log("Starting");
// Validate and update our current component stateif (started)
thrownew LifecycleException
(sm.getString("standardManager.alreadyStarted"));
lifecycle.fireLifecycleEvent(START_EVENT, null);
started = true;
// Force initialization of the random number generatorif (debug >= 1)
log("Force random number initialization starting");
String dummy = generateSessionId();
if (debug >= 1)
log("Force random number initialization completed");
// Load unloaded sessions, if anytry {
//用于加载持久化的session,加载以后放入sessions(hashMap)中
load();
} catch (Throwable t) {
log(sm.getString("standardManager.managerLoad"), t);
}
// Start the background reaper thread
threadStart();
}
//启动一个管理器线程,用于实现自动重新加载privatevoidthreadStart() {
if (thread != null)
return;
threadDone = false;
threadName = "StandardManager[" + container.getName() + "]";
thread = new Thread(this, threadName);
thread.setDaemon(true);
thread.setContextClassLoader(container.getLoader().getClassLoader());
thread.start();
}
/**
* The background thread that checks for session timeouts and shutdown.
*/publicvoidrun() {
// Loop until the termination semaphore is setwhile (!threadDone) {
threadSleep();
processExpires();
}
}
privatevoidthreadSleep() {
try {
Thread.sleep(checkInterval * 1000L);
} catch (InterruptedException e) {
;
}
}
/**
* Invalidate all sessions that have expired.
*///管理StandardSession中session,去除无效的sessionprivatevoidprocessExpires() {
long timeNow = System.currentTimeMillis();
//获取存活的sessions
Session sessions[] = findSessions();
for (int i = 0; i < sessions.length; i++) {
StandardSession session = (StandardSession) sessions[i];
//有效,则不移除if (!session.isValid())
continue;
int maxInactiveInterval = session.getMaxInactiveInterval();
//如果设置最大存活时间是-1,则不终止if (maxInactiveInterval < 0)
continue;
int timeIdle = // Truncate, do not round up
(int) ((timeNow - session.getLastAccessedTime()) / 1000L);
if (timeIdle >= maxInactiveInterval) {
try {
session.expire();
} catch (Throwable t) {
log(sm.getString("standardManager.expireException"), t);
}
}
}
}
2.StandardManager中整个停止过程
public
void
stop() throws LifecycleException {
if (debug >= 1)
log("Stopping");
// Validate and update our current component stateif (!started)
thrownew LifecycleException
(sm.getString("standardManager.notStarted"));
lifecycle.fireLifecycleEvent(STOP_EVENT, null);
started = false;
// Stop the background reaper thread
threadStop();
// Write out sessionstry {
//将存活的session持久化
unload();
} catch (IOException e) {
log(sm.getString("standardManager.managerUnload"), e);
}
// Expire all active sessions
Session sessions[] = findSessions();
for (int i = 0; i < sessions.length; i++) {
StandardSession session = (StandardSession) sessions[i];
if (!session.isValid())
continue;
try {
//终止所有的session
session.expire();
} catch (Throwable t) {
;
}
}
// Require a new random number generator if we are restartedthis.random = null;
privatevoidthreadStop() {
if (thread == null)
return;
threadDone = true;
//将当前线程设置为中断状态
thread.interrupt();
try {
//当前线程被挂起,直达thread线程结束才运行改线程
thread.join();
} catch (InterruptedException e) {
;
}
thread = null;
}
1.StandardManager中创建一个session
public Session createSession() {
if ((maxActiveSessions >= 0) &&
(sessions.size() >= maxActiveSessions))
thrownew IllegalStateException
(sm.getString("standardManager.createSession.ise"));
//实际调用的是ManagerBase中的creatSession()方法return (super.createSession());
}
//ManagerBase类中creatSession方法public Session createSession() {
// Recycle or create a Session instance
Session session = null;
synchronized (recycled) {
int size = recycled.size();
if (size > 0) {
session = (Session) recycled.get(size - 1);
recycled.remove(size - 1);
}
}
if (session != null)
session.setManager(this);
else
session = new StandardSession(this);
// Initialize the properties of the new session and return it
session.setNew(true);
session.setValid(true);
session.setCreationTime(System.currentTimeMillis());
session.setMaxInactiveInterval(this.maxInactiveInterval);
String sessionId = generateSessionId();
String jvmRoute = getJvmRoute();
// @todo Move appending of jvmRoute generateSessionId()???if (jvmRoute != null) {
sessionId += ‘.‘ + jvmRoute;
session.setId(sessionId);
}
/*
synchronized (sessions) {
while (sessions.get(sessionId) != null) // Guarantee uniqueness
sessionId = generateSessionId();
}
*/
session.setId(sessionId);
return (session);
}
原文:http://blog.csdn.net/u010149189/article/details/51346557
内容总结
以上是互联网集市为您收集整理的Tomcat中session详解(源码阅读)全部内容,希望文章能够帮你解决Tomcat中session详解(源码阅读)所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。