1、Session的介紹
關於Session
會話:從啟動一個Session到關閉這個Session作為一個會話,是對客戶端和服務器端交互的一種封裝,帶有時效性
會話的產生:
一般從容器中產生
Web container:Web容器,如Tomcat,這些容器對Session進行了實現,可以產生Session
EJB Stateful Session Beans:比較少用
會話的應用:
Mobile
Web
分布式集群
Shiro Session
基於POJO
可以自定義Session存儲的方式,保存到內存、文件、數據庫都可以
容器無關的集群
客戶端訪問多樣化
事件監聽
主機地址記憶,可以知道由哪台主機創建
Web使用透明化,不需要關心Session怎么創建,只需要知道如何使用
支持SSO,單點登錄
使用Session
Subject currentUser = SecurityUtils.getSubject(); Session session = currentUser.getSession(true); session.setAttribute("someKey", somValue);
subject.getSession(flag)
如果subject存在session,直接返回session
如果subject不存在session,flag=true,則創建一個新的Ssssion並返回
如果subject不存在session,flag=false,則返回null
類似servlet中的Session
支持所有應用,適合但不限於Web應用
2、SessionManager
DefaultSessionManager:默認實現
Session Timeout:Session的有效期
Session Listeners:面向事件、實現SessionListener接口
Session Storage:Session的保存形式
SessionDAO接口抽象
in-memory-only:默認,使用內存保存Session
EHCache SessionDAO:使用磁盤保存Session的實現
EhCache SessionDAO的使用
配置ehcache.xml
Session Cache Name
Session IDs
SessionIdGenerator組件:用於生成SessionID
JavaUuidSessionIdGenerator:默認實現,使用Java的uuid
自定義
Session Validation
判斷Session是否過期
Lazy Validation:使用的時候才判斷
Session孤兒(orphan):使用Lazy時,某些Session過期了,仍長期存在。
SessionValidationScheduler
定期刪除Session孤兒
ExecutorServiceSessionValidationScheduler:默認實現
自定義SessionValidationScheduler
關閉Session Validation
關閉Session刪除功能
3、Session集群
用於實現Session的集群
Shiro支持分布式緩存
Web容器環境
Native環境
基於POJO多層架構
支持集群的SessionDAO
透明的SessionManager
支持集成多種分布式緩存服務器
EnterpriseCacheSessionDAO
activeSessionsCache
第三方集成
Ehcache+Terracotta
Zookeeper
4、Session和用戶狀態
有狀態的應用
Shiro默認使用Session保存認證狀態
通過SessionId獲取用戶狀態
無狀態的應用
自定義混合方案
SessionStorageEvaluator