• shiro会话管理


    目录

    1. 会话管理

    2. 基础组件

     2.1 SessionManager

     2.2 SessionListener 

     2.3 SessionDao 

     2.4 会话验证

    3. 缓存管理 

    3.1 为什么要使用缓存 

    3.2 什么是ehcache 

    3.3 ehcache特点 

    4. 添加pom依赖 

    5. 添加相关配置文件

     5.1 ehcache.xml (添加到main\resources目录下)

     5.2 spring-ehcache.xml,shiro与ehcache整合(添加到main\resources目录下)

     5.3 修改spring-shiro.xml文件,添加相关配置 (完整,可直接覆盖即可)


     

     1. 会话管理

    Shiro提供了完整的企业级会话管理功能,不依赖于底层容器(如Tomcat),不管是J2SE还是J2EE环境都可以使用,提供了会话管理,会话事件监听,会话存储/持久化,容器无关的集群,失效/过期支持,对Web的透明支持,SSO单点登录的支持等特性。所谓会话,即用户访问应用时保持的连接关系,在多次交互中应用能够识别出当前访问的用户是谁,且可以在多次交互中保存一些数据。如访问一些网站时登录成功后,网站可以记住用户,且在退出之前都可以识别当前用户是谁。 

    2. 基础组件

     2.1 SessionManager

    会话管理器管理着应用中所有 Subject 的会话的创建、维护、删除、失效、验证等工作。是Shiro 的核心组件,顶层组件SecurityManager直接继承了SessionManager,且提供了SessionsSecurityManager实现直接把会话管理委托给相应的SessionManager
    1)DefaultSessionManager:使用的默认实现,用于JavaSE环境
    2)ServletContainerSessionManager:使用的默认实现,用于Web环境,其直接使用Servlet容器的会话
    3)DefaultWebSessionManager:用于Web环境的实现,可以替代ServletContainerSessionManager,自己维护着会话,直接废弃了Servlet容器的会话管理 

     2.2 SessionListener 

      SessionListener会话监听器用于监听会话创建、过期及停止事件。
      实现方式:
      1)实现SessionListener,必须实现所有方法
      2)继承SessionListenerAdapter,重写指定方法 

     相关API: 

      1)onStart(Session session):监听会话创建事件
      2)onStop(Session session):监听会话销毁事件
      3)onExpiration(Session session):监听会话过期事件 

     2.3 SessionDao 

    Shiro提供SessionDAO用于会话的CRUD,即DAO(Data Access Object)模式实现。
    1)AbstractSessionDAO:提供了SessionDAO的基础实现,如生成会话ID等
    2)CachingSessionDAO:提供了对开发者透明的会话缓存的功能,需要设置相应的CacheManager 
    3)MemorySessionDAO:直接在内存中进行会话维护(默认方式)
    4)EnterpriseCacheSessionDAO:提供了缓存功能的会话维护,默认情况下使用MapCache实现,内部使用ConcurrentHashMap保存缓存的会话。

     相关API: 

      如DefaultSessionManager在创建完session后会调用该方法;
      如保存到关系数据库/文件系统/NoSQL数据库;
      即可以实现会话的持久化;返回会话ID;主要此处返回的ID.equals(session.getId());  
      Serializable create(Session session);
      根据会话ID获取会话  
      Session readSession(Serializable sessionId) throws UnknownSessionException;  
      更新会话;如更新会话最后访问时间/停止会话/设置超时时间/设置移除属性等会调用  
      void update(Session session) throws UnknownSessionException;  
      删除会话;当会话过期/会话停止(如用户退出时)会调用  
      void delete(Session session);  
      获取当前所有活跃用户,如果用户量多此方法影响性能  
      Collection getActiveSessions();

     2.4 会话验证


    1)Shiro提供了会话验证调度器,用于定期的验证会话是否已过期,如果过期将停止会话。
    2)出于性能考虑,一般情况下都是获取会话的同时来验证会话是否过期并停止会话的;但是如果在Web环境中,如果用户不主动退出是不知道会话是否过期的,因此需要定义的检测会话是否过期,Shiro提供了会话验证调度器来定期检查会话是否过期,SessionValidationScheduler 。
    3)Shrio也提供了使用Quartz会话验证调度器 QuartzSessionValidationScheduler 。 

    3. 缓存管理 

    3.1 为什么要使用缓存 

    在没有使用缓存的情况下,我们每次发送请求都会调用一次doGetAuthorizationInfo方法来进  行用户的授权操作,但是我们知道,一个用户具有的权限一般不会频繁的修改,也就是每次  授权的内容都是一样的,所以我们希望在用户登录成功的第一次授权成功后将用户的权限保  存在缓存中,下一次请求授权的话就直接从缓存中获取,这样效率会更高一些

     3.2 什么是ehcache 

    Ehcache是现在最流行的纯Java开源缓存框架,配置简单、结构清晰、功能强大。是Hibernate中默认CacheProvider。Ehcache是一种广泛使用的开源Java分布式缓存。主要面向通用缓存,Java EE和轻量级容器。它具有内存和磁盘存储,缓存加载器,缓存扩展,缓存异常处理程序,一个gzip缓存servlet过滤器,支持REST和SOAP api等特点。 

    • 本章介绍的是2.X版本,3.x的版本和2.x的版本API差异比较大 

    3.3 ehcache特点 

    1) 够快
     Ehcache的发行有一段时长了,经过几年的努力和不计其数的性能测试,Ehcache终被设计于large, high concurrency systems.
     2) 够简单
     开发者提供的接口非常简单明了,从Ehcache的搭建到运用运行仅仅需要的是你宝贵的几分钟。其实很多开发者都不知道自己用在用Ehcache,Ehcache被广泛的运用于其他的开源项目
     3) 够袖珍

    关于这点的特性,官方给了一个很可爱的名字small foot print ,一般Ehcache的发布版本不会到2M,V 2.2.3 才 668KB。
    4) 够轻量
    核心程序仅仅依赖slf4j这一个包,没有之一!
    5) 好扩展
    Ehcache提供了对大数据的内存和硬盘的存储,最近版本允许多实例、保存对象高灵活性、  提供LRU、LFU、FIFO淘汰算法,基础属性支持热配置、支持的插件多
    6) 监听器
    缓存管理器监听器 (CacheManagerListener)和 缓存监听器(CacheEvenListener),做一些统计或数据一致性广播挺好用的
    7) 分布式缓存
    从Ehcache 1.2开始,支持高性能的分布式缓存,兼具灵活性和扩展性 

    4. 添加pom依赖 

    • 复制下方依赖可直接覆盖 
    1. "1.0" encoding="UTF-8"?>
    2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    4. <modelVersion>4.0.0modelVersion>
    5. <groupId>com.jmhgroupId>
    6. <artifactId>mybatis03artifactId>
    7. <version>1.0-SNAPSHOTversion>
    8. <packaging>warpackaging>
    9. <name>mybatis03 Maven Webappname>
    10. <url>http://www.example.comurl>
    11. <properties>
    12. <spring.version>5.0.2.RELEASEspring.version>
    13. <maven.compiler.source>1.8maven.compiler.source>
    14. <maven.compiler.target>1.8maven.compiler.target>
    15. <jackson.version>2.9.3jackson.version>
    16. <shiro.version>1.2.5shiro.version>
    17. <slf4j.version>1.7.7slf4j.version>
    18. <log4j2.version>2.9.1log4j2.version>
    19. properties>
    20. <dependencies>
    21. <dependency>
    22. <groupId>org.springframeworkgroupId>
    23. <artifactId>spring-coreartifactId>
    24. <version>${spring.version}version>
    25. dependency>
    26. <dependency>
    27. <groupId>org.springframeworkgroupId>
    28. <artifactId>spring-beansartifactId>
    29. <version>${spring.version}version>
    30. dependency>
    31. <dependency>
    32. <groupId>org.springframeworkgroupId>
    33. <artifactId>spring-contextartifactId>
    34. <version>${spring.version}version>
    35. dependency>
    36. <dependency>
    37. <groupId>org.springframeworkgroupId>
    38. <artifactId>spring-ormartifactId>
    39. <version>${spring.version}version>
    40. dependency>
    41. <dependency>
    42. <groupId>org.springframeworkgroupId>
    43. <artifactId>spring-txartifactId>
    44. <version>${spring.version}
    45. version>
    46. dependency>
    47. <dependency>
    48. <groupId>org.springframeworkgroupId>
    49. <artifactId>spring-aspectsartifactId>
    50. <version>${spring.version}version>
    51. dependency>
    52. <dependency>
    53. <groupId>org.springframeworkgroupId>
    54. <artifactId>spring-webartifactId>
    55. <version>${spring.version}version>
    56. dependency>
    57. <dependency>
    58. <groupId>org.springframeworkgroupId>
    59. <artifactId>spring-testartifactId>
    60. <version>${spring.version}version>
    61. dependency>
    62. <dependency>
    63. <groupId>org.springframeworkgroupId>
    64. <artifactId>spring-webmvcartifactId>
    65. <version>${spring.version}version>
    66. dependency>
    67. <dependency>
    68. <groupId>jstlgroupId>
    69. <artifactId>jstlartifactId>
    70. <version>1.2version>
    71. dependency>
    72. <dependency>
    73. <groupId>taglibsgroupId>
    74. <artifactId>standardartifactId>
    75. <version>1.1.2version>
    76. dependency>
    77. <dependency>
    78. <groupId>com.fasterxml.jackson.coregroupId>
    79. <artifactId>jackson-databindartifactId>
    80. <version>${jackson.version}version>
    81. <exclusions>
    82. <exclusion>
    83. <artifactId>jackson-annotationsartifactId>
    84. <groupId>com.fasterxml.jackson.coregroupId>
    85. exclusion>
    86. exclusions>
    87. dependency>
    88. <dependency>
    89. <groupId>com.fasterxml.jackson.coregroupId>
    90. <artifactId>jackson-coreartifactId>
    91. <version>${jackson.version}version>
    92. dependency>
    93. <dependency>
    94. <groupId>com.fasterxml.jackson.coregroupId>
    95. <artifactId>jackson-annotationsartifactId>
    96. <version>${jackson.version}version>
    97. dependency>
    98. <dependency>
    99. <groupId>commons-fileuploadgroupId>
    100. <artifactId>commons-fileuploadartifactId>
    101. <version>1.3.3version>
    102. dependency>
    103. <dependency>
    104. <groupId>org.hibernategroupId>
    105. <artifactId>hibernate-validatorartifactId>
    106. <version>6.0.7.Finalversion>
    107. dependency>
    108. <dependency>
    109. <groupId>junitgroupId>
    110. <artifactId>junitartifactId>
    111. <version>4.12version>
    112. <scope>testscope>
    113. dependency>
    114. <dependency>
    115. <groupId>javax.servletgroupId>
    116. <artifactId>javax.servlet-apiartifactId>
    117. <version>4.0.0version>
    118. <scope>providedscope>
    119. dependency>
    120. <dependency>
    121. <groupId>org.mybatisgroupId>
    122. <artifactId>mybatisartifactId>
    123. <version>3.4.5version>
    124. dependency>
    125. <dependency>
    126. <groupId>com.github.pagehelpergroupId>
    127. <artifactId>pagehelperartifactId>
    128. <version>5.1.2version>
    129. dependency>
    130. <dependency>
    131. <groupId>org.mybatisgroupId>
    132. <artifactId>mybatis-springartifactId>
    133. <version>1.3.1version>
    134. dependency>
    135. <dependency>
    136. <groupId>mysqlgroupId>
    137. <artifactId>mysql-connector-javaartifactId>
    138. <version>5.1.44version>
    139. dependency>
    140. <dependency>
    141. <groupId>org.apache.commonsgroupId>
    142. <artifactId>commons-dbcp2artifactId>
    143. <version>2.1.1version>
    144. dependency>
    145. <dependency>
    146. <groupId>org.apache.commonsgroupId>
    147. <artifactId>commons-pool2artifactId>
    148. <version>2.4.3version>
    149. dependency>
    150. <dependency>
    151. <groupId>org.slf4jgroupId>
    152. <artifactId>slf4j-apiartifactId>
    153. <version>${slf4j.version}version>
    154. dependency>
    155. <dependency>
    156. <groupId>org.slf4jgroupId>
    157. <artifactId>jcl-over-slf4jartifactId>
    158. <version>${slf4j.version}version>
    159. <scope>runtimescope>
    160. <exclusions>
    161. <exclusion>
    162. <artifactId>slf4j-apiartifactId>
    163. <groupId>org.slf4jgroupId>
    164. exclusion>
    165. exclusions>
    166. dependency>
    167. <dependency>
    168. <groupId>org.apache.logging.log4jgroupId>
    169. <artifactId>log4j-slf4j-implartifactId>
    170. <version>${log4j2.version}version>
    171. <exclusions>
    172. <exclusion>
    173. <artifactId>slf4j-apiartifactId>
    174. <groupId>org.slf4jgroupId>
    175. exclusion>
    176. exclusions>
    177. dependency>
    178. <dependency>
    179. <groupId>org.apache.logging.log4jgroupId>
    180. <artifactId>log4j-coreartifactId>
    181. <version>${log4j2.version}version>
    182. dependency>
    183. <dependency>
    184. <groupId>org.apache.logging.log4jgroupId>
    185. <artifactId>log4j-apiartifactId>
    186. <version>${log4j2.version}version>
    187. dependency>
    188. <dependency>
    189. <groupId>org.apache.logging.log4jgroupId>
    190. <artifactId>log4j-webartifactId>
    191. <version>${log4j2.version}version>
    192. dependency>
    193. <dependency>
    194. <groupId>com.lmaxgroupId>
    195. <artifactId>disruptorartifactId>
    196. <version>3.2.0version>
    197. dependency>
    198. <dependency>
    199. <groupId>org.projectlombokgroupId>
    200. <artifactId>lombokartifactId>
    201. <version>1.18.20version>
    202. <scope>providedscope>
    203. dependency>
    204. <dependency>
    205. <groupId>org.apache.shirogroupId>
    206. <artifactId>shiro-coreartifactId>
    207. <version>${shiro.version}version>
    208. dependency>
    209. <dependency>
    210. <groupId>org.apache.shirogroupId>
    211. <artifactId>shiro-webartifactId>
    212. <version>${shiro.version}version>
    213. dependency>
    214. <dependency>
    215. <groupId>org.apache.shirogroupId>
    216. <artifactId>shiro-springartifactId>
    217. <version>${shiro.version}version>
    218. dependency>
    219. <dependency>
    220. <groupId>net.sf.ehcachegroupId>
    221. <artifactId>ehcacheartifactId>
    222. <version>2.10.0version>
    223. dependency>
    224. <dependency>
    225. <groupId>org.apache.shirogroupId>
    226. <artifactId>shiro-ehcacheartifactId>
    227. <version>1.4.1version>
    228. dependency>
    229. <dependency>
    230. <groupId>org.springframeworkgroupId>
    231. <artifactId>spring-context-supportartifactId>
    232. <version>${spring.version}version>
    233. dependency>
    234. dependencies>
    235. <build>
    236. <finalName>shiro02finalName>
    237. <resources>
    238. <resource>
    239. <directory>src/main/javadirectory>
    240. <includes>
    241. <include>**/*.xmlinclude>
    242. includes>
    243. resource>
    244. <resource>
    245. <directory>src/main/resourcesdirectory>
    246. <includes>
    247. <include>jdbc.propertiesinclude>
    248. <include>*.xmlinclude>
    249. includes>
    250. resource>
    251. resources>
    252. <pluginManagement>
    253. <plugins>
    254. <plugin>
    255. <groupId>org.mybatis.generatorgroupId>
    256. <artifactId>mybatis-generator-maven-pluginartifactId>
    257. <version>1.3.2version>
    258. <dependencies>
    259. <dependency>
    260. <groupId>mysqlgroupId>
    261. <artifactId>mysql-connector-javaartifactId>
    262. <version>5.1.44version>
    263. dependency>
    264. dependencies>
    265. <configuration>
    266. <overwrite>trueoverwrite>
    267. configuration>
    268. plugin>
    269. plugins>
    270. pluginManagement>
    271. build>
    272. project>

    5. 添加相关配置文件

     5.1 ehcache.xml (添加到main\resources目录下)

    1. "1.0" encoding="UTF-8"?>
    2. <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    3. xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
    4. updateCheck="false">
    5. <diskStore path="java.io.tmpdir"/>
    6. <defaultCache eternal="false" maxElementsInMemory="1000" overflowToDisk="false" diskPersistent="false"
    7. timeToIdleSeconds="0" timeToLiveSeconds="600" memoryStoreEvictionPolicy="LRU"/>
    8. <cache name="stuCache" eternal="false" maxElementsInMemory="100"
    9. overflowToDisk="false" diskPersistent="false" timeToIdleSeconds="0"
    10. timeToLiveSeconds="300" memoryStoreEvictionPolicy="LRU"/>
    11. ehcache>

     5.2 spring-ehcache.xml,shiro与ehcache整合(添加到main\resources目录下)

    1. "1.0" encoding="UTF-8"?>
    2. <beans xmlns="http://www.springframework.org/schema/beans"
    3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    4. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    5. <bean id="cacheManagerFactory" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
    6. <property name="configLocation" value="classpath:ehcache.xml"/>
    7. <property name="shared" value="true"/>
    8. bean>
    9. <bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
    10. <property name="cacheManager" ref="cacheManagerFactory"/>
    11. bean>
    12. beans>
    • 同时也要导入到spring.xml文件中 
    <import resource="spring-ehcache.xml"/>

     5.3 修改spring-shiro.xml文件,添加相关配置 (完整,可直接覆盖即可)

     需要修改创建会话监听器的位置到你自己的那里(资源在下方已提供)

    1. "1.0" encoding="UTF-8"?>
    2. <beans xmlns="http://www.springframework.org/schema/beans"
    3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    4. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    5. <bean id="shiroRealm" class="com.jmh.shiro.utils.Realm">
    6. <property name="cachingEnabled" value="true"/>
    7. <property name="authorizationCachingEnabled" value="true"/>
    8. <property name="authorizationCacheName" value="shiroAuthzCache"/>
    9. <property name="credentialsMatcher">
    10. <bean id="credentialsMatcher" class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
    11. <property name="hashAlgorithmName" value="md5"/>
    12. <property name="hashIterations" value="1024"/>
    13. <property name="storedCredentialsHexEncoded" value="true"/>
    14. bean>
    15. property>
    16. bean>
    17. <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
    18. <property name="realm" ref="shiroRealm" />
    19. <property name="cacheManager" ref="cacheManager"/>
    20. bean>
    21. <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
    22. <property name="securityManager" ref="securityManager" />
    23. <property name="loginUrl" value="/home/index.shtml"/>
    24. <property name="filterChainDefinitions">
    25. <value>
    26. /user/login=anon
    27. /book/**=authc
    28. /common/**=authc
    29. value>
    30. property>
    31. bean>
    32. <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>
    33. <bean id="sessionIdGenerator" class="org.apache.shiro.session.mgt.eis.JavaUuidSessionIdGenerator">
    34. bean>
    35. <bean id="customSessionDao" class="org.apache.shiro.session.mgt.eis.MemorySessionDAO">
    36. <property name="sessionIdGenerator" ref="sessionIdGenerator"/>
    37. bean>
    38. <bean id="shiroSessionListener" class="com.jmh.shiro.utils.ShiroSessionListener"/>
    39. <bean id="sessionIdCookie" class="org.apache.shiro.web.servlet.SimpleCookie">
    40. <constructor-arg value="shiro.session"/>
    41. <property name="maxAge" value="-1"/>
    42. <property name="httpOnly" value="true"/>
    43. bean>
    44. <bean id="sessionManager" class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager">
    45. <property name="globalSessionTimeout" value="180000"/>
    46. <property name="sessionDAO" ref="customSessionDao"/>
    47. <property name="sessionValidationInterval" value="1800000"/>
    48. <property name="deleteInvalidSessions" value="true"/>
    49. <property name="sessionListeners">
    50. <list>
    51. <ref bean="shiroSessionListener"/>
    52. list>
    53. property>
    54. <property name="sessionIdCookie" ref="sessionIdCookie"/>
    55. bean>
    56. beans>
    •  ShiroSessionListener

    1. package com.jmh.shiro.utils;
    2. import org.apache.shiro.session.Session;
    3. import org.apache.shiro.session.SessionListener;
    4. /**
    5. * SessionListener会话监听器用于监听会话创建、过期及停止事件。
    6. * 实现方式:
    7. * 1)实现SessionListener,必须实现所有方法
    8. * 2)继承SessionListenerAdapter,重写指定方法
    9. * 相关API:
    10. * 1)onStart(Session session):监听会话创建事件
    11. * 2)onStop(Session session):监听会话销毁事件
    12. * 3)onExpiration(Session session):监听会话过期事件
    13. */
    14. public class ShiroSessionListener implements SessionListener {
    15. @Override
    16. public void onStart(Session session) {
    17. System.out.println("监听会话创建事件" + session.getId());
    18. }
    19. @Override
    20. public void onStop(Session session) {
    21. System.out.println("监听会话销毁事件" + session.getId());
    22. }
    23. @Override
    24. public void onExpiration(Session session) {
    25. System.out.println("监听会话过期事件" + session.getId());
    26. }
    27. }

      注:这里只开启了授权缓存,避免每次请求都要重新查询授权数据!!! 

  • 相关阅读:
    2.4路由日志管理
    Mysql视图和触发器
    424. 替换后的最长重复字符 ●●
    Docker安装启动Mysql
    【区块链实战】——实现简易版dapp【对于用户年龄的获取和更新】
    electron使用typescript
    LRU Cache【理论讲解 + 代码实现】
    Anaconda安装教程(Windows环境下)
    pytorch 笔记:index_select
    【秋招必备】JVM性能调优面试题(2022最新版)
  • 原文地址:https://blog.csdn.net/m0_63300795/article/details/126475729