经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » Java相关 » Java » 查看文章
shiro源码篇 - shiro的session共享,你值得拥有
来源:cnblogs  作者:youzhibing2904  时间:2018/10/30 9:04:04  对本文有异议

前言

  开心一刻

    老师对小明说:"乳就是小的意思,比如乳猪就是小猪,乳名就是小名,请你用乳字造个句"
    小明:"我家很穷,只能住在40平米的乳房"
    老师:"..., 这个不行,换一个"
    小明:"我每天上学都要跳过我家门口的一条乳沟"
    老师:"......, 这个也不行,再换一个"
    小明:"老师,我想不出来了,把我的乳头都想破了!"

  路漫漫其修远兮,吾将上下而求索!

  github:https://github.com/youzhibing

  码云(gitee):https://gitee.com/youzhibing

前情回顾

  shiro的session创建session的查询、更新、过期、删除中,shiro对session的操作基本都讲到了,但还缺一个session共享没有讲解;session共享的原理其实在定义session管理一文已经讲过了,本文不讲原理,只看看shiro的session共享的实现。

  为何需要session共享

    如果是单机应用,那么谈不上session共享,session放哪都无所谓,不在乎放到默认的servlet容器中,还是抽出来放到单独的地方;

    也就是说session共享是针对集群(或分布式、或分布式集群)的;如果不做session共享,仍然采用默认的方式(session存放到默认的servlet容器),当我们的应用是以集群的方式发布的时候,同个用户的请求会被分发到不同的集群节点(分发依赖具体的负载均衡规则),那么每个处理同个用户请求的节点都会重新生成该用户的session,这些session之间是毫无关联的。那么同个用户的请求会被当成多个不同用户的请求,这肯定是不行的。

  如何实现session共享

    实现方式其实有很多,甚至可以不做session共享,具体有哪些,大家自行去查资料。本文提供一种方式:redis实现session共享,就是将session从servlet容器抽出来,放到redis中存储,所有集群节点都从redis中对session进行操作。

SessionDAO

  SessionDAO其实是用于session持久化的,但里面有缓存部分,具体细节我们往下看

  shiro已有SessionDAO的实现如下

  SessionDAO接口提供的方法如下

  1. package org.apache.shiro.session.mgt.eis;
  2. import org.apache.shiro.session.Session;
  3. import org.apache.shiro.session.UnknownSessionException;
  4. import java.io.Serializable;
  5. import java.util.Collection;
  6. /**
  7. * 从EIS操作session的规范(EIS:例如关系型数据库, 文件系统, 持久化缓存等等, 具体依赖DAO实现)
  8. * 提供了典型的CRUD的方法:create, readSession, update, delete
  9. */
  10. public interface SessionDAO {
  11. /**
  12. * 插入一个新的sesion记录到EIS
  13. */
  14. Serializable create(Session session);
  15. /**
  16. * 根据会话ID获取会话
  17. */
  18. Session readSession(Serializable sessionId) throws UnknownSessionException;
  19. /**
  20. * 更新session; 如更新session最后访问时间/停止会话/设置超时时间/设置移除属性等会调用
  21. */
  22. void update(Session session) throws UnknownSessionException;
  23. /**
  24. * 删除session; 当会话过期/会话停止(如用户退出时)会调用
  25. */
  26. void delete(Session session);
  27. /**
  28. * 获取当前所有活跃session, 所有状态不是stopped/expired的session
  29. * 如果用户量多此方法影响性能
  30. */
  31. Collection<Session> getActiveSessions();
  32. }
View Code

    SessionDAO给出了从持久层(一般而言是关系型数据库)操作session的标准。

  AbstractSessionDAO提供了SessionDAO的基本实现,如下

  1. package org.apache.shiro.session.mgt.eis;
  2. import org.apache.shiro.session.Session;
  3. import org.apache.shiro.session.UnknownSessionException;
  4. import org.apache.shiro.session.mgt.SimpleSession;
  5. import java.io.Serializable;
  6. /**
  7. * SessionDAO的抽象实现, 在会话创建和读取时做一些健全性检查,并在需要时允许可插入的会话ID生成策略.
  8. * SessionDAO的update和delete则留给子类来实现
  9. * EIS需要子类自己实现
  10. */
  11. public abstract class AbstractSessionDAO implements SessionDAO {
  12. /**
  13. * sessionId生成器
  14. */
  15. private SessionIdGenerator sessionIdGenerator;
  16. public AbstractSessionDAO() {
  17. this.sessionIdGenerator = new JavaUuidSessionIdGenerator(); // 指定JavaUuidSessionIdGenerator为默认sessionId生成器
  18. }
  19. /**
  20. * 获取sessionId生成器
  21. */
  22. public SessionIdGenerator getSessionIdGenerator() {
  23. return sessionIdGenerator;
  24. }
  25. /**
  26. * 设置sessionId生成器
  27. */
  28. public void setSessionIdGenerator(SessionIdGenerator sessionIdGenerator) {
  29. this.sessionIdGenerator = sessionIdGenerator;
  30. }
  31. /**
  32. * 生成一个新的sessionId, 并将它应用到session实例
  33. */
  34. protected Serializable generateSessionId(Session session) {
  35. if (this.sessionIdGenerator == null) {
  36. String msg = "sessionIdGenerator attribute has not been configured.";
  37. throw new IllegalStateException(msg);
  38. }
  39. return this.sessionIdGenerator.generateId(session);
  40. }
  41. /**
  42. * SessionDAO中create实现; 将创建的sesion保存到EIS.
  43. * 子类doCreate方法的代理,具体的细节委托给了子类的doCreate方法
  44. */
  45. public Serializable create(Session session) {
  46. Serializable sessionId = doCreate(session);
  47. verifySessionId(sessionId);
  48. return sessionId;
  49. }
  50. /**
  51. * 保证从doCreate返回的sessionId不是null,并且不是已经存在的.
  52. * 目前只实现了null校验,是否已存在是没有校验的,可能shiro的开发者会在后续补上吧.
  53. */
  54. private void verifySessionId(Serializable sessionId) {
  55. if (sessionId == null) {
  56. String msg = "sessionId returned from doCreate implementation is null. Please verify the implementation.";
  57. throw new IllegalStateException(msg);
  58. }
  59. }
  60. /**
  61. * 分配sessionId给session实例
  62. */
  63. protected void assignSessionId(Session session, Serializable sessionId) {
  64. ((SimpleSession) session).setId(sessionId);
  65. }
  66. /**
  67. * 子类通过实现此方法来持久化Session实例到EIS.
  68. */
  69. protected abstract Serializable doCreate(Session session);
  70. /**
  71. * SessionDAO中readSession实现; 通过sessionId从EIS获取session对象.
  72. * 子类doReadSession方法的代理,具体的获取细节委托给了子类的doReadSession方法.
  73. */
  74. public Session readSession(Serializable sessionId) throws UnknownSessionException {
  75. Session s = doReadSession(sessionId);
  76. if (s == null) {
  77. throw new UnknownSessionException("There is no session with id [" + sessionId + "]");
  78. }
  79. return s;
  80. }
  81. /**
  82. * 子类通过实现此方法从EIS获取session实例
  83. */
  84. protected abstract Session doReadSession(Serializable sessionId);
  85. }
View Code

    SessionDao的基本实现,实现了SessionDao的create、readSession(具体还是依赖AbstractSessionDAO子类的doCreate、doReadSession实现);同时加入了自己的sessionId生成器,负责sessionId的操作。

  CachingSessionDAO提供了session缓存的功能,如下

  1. package org.apache.shiro.session.mgt.eis;
  2. import org.apache.shiro.cache.Cache;
  3. import org.apache.shiro.cache.CacheManager;
  4. import org.apache.shiro.cache.CacheManagerAware;
  5. import org.apache.shiro.session.Session;
  6. import org.apache.shiro.session.UnknownSessionException;
  7. import org.apache.shiro.session.mgt.ValidatingSession;
  8. import java.io.Serializable;
  9. import java.util.Collection;
  10. import java.util.Collections;
  11. /**
  12. * 应用层与持久层(EIS,如关系型数据库、文件系统、NOSQL)之间的缓存层实现
  13. * 缓存着所有激活状态的session
  14. * 实现了CacheManagerAware,会在shiro加载的过程中调用此对象的setCacheManager方法
  15. */
  16. public abstract class CachingSessionDAO extends AbstractSessionDAO implements CacheManagerAware {
  17. /**
  18. * 激活状态的sesion的默认缓存名
  19. */
  20. public static final String ACTIVE_SESSION_CACHE_NAME = "shiro-activeSessionCache";
  21. /**
  22. * 缓存管理器,用来获取session缓存
  23. */
  24. private CacheManager cacheManager;
  25. /**
  26. * 用来缓存session的缓存实例
  27. */
  28. private Cache<Serializable, Session> activeSessions;
  29. /**
  30. * session缓存名, 默认是ACTIVE_SESSION_CACHE_NAME.
  31. */
  32. private String activeSessionsCacheName = ACTIVE_SESSION_CACHE_NAME;
  33. public CachingSessionDAO() {
  34. }
  35. /**
  36. * 设置缓存管理器
  37. */
  38. public void setCacheManager(CacheManager cacheManager) {
  39. this.cacheManager = cacheManager;
  40. }
  41. /**
  42. * 获取缓存管理器
  43. */
  44. public CacheManager getCacheManager() {
  45. return cacheManager;
  46. }
  47. /**
  48. * 获取缓存实例的名称,也就是获取activeSessionsCacheName的值
  49. */
  50. public String getActiveSessionsCacheName() {
  51. return activeSessionsCacheName;
  52. }
  53. /**
  54. * 设置缓存实例的名称,也就是设置activeSessionsCacheName的值
  55. */
  56. public void setActiveSessionsCacheName(String activeSessionsCacheName) {
  57. this.activeSessionsCacheName = activeSessionsCacheName;
  58. }
  59. /**
  60. * 获取缓存实例
  61. */
  62. public Cache<Serializable, Session> getActiveSessionsCache() {
  63. return this.activeSessions;
  64. }
  65. /**
  66. * 设置缓存实例
  67. */
  68. public void setActiveSessionsCache(Cache<Serializable, Session> cache) {
  69. this.activeSessions = cache;
  70. }
  71. /**
  72. * 获取缓存实例
  73. * 注意:不会返回non-null值
  74. *
  75. * @return the active sessions cache instance.
  76. */
  77. private Cache<Serializable, Session> getActiveSessionsCacheLazy() {
  78. if (this.activeSessions == null) {
  79. this.activeSessions = createActiveSessionsCache();
  80. }
  81. return activeSessions;
  82. }
  83. /**
  84. * 创建缓存实例
  85. */
  86. protected Cache<Serializable, Session> createActiveSessionsCache() {
  87. Cache<Serializable, Session> cache = null;
  88. CacheManager mgr = getCacheManager();
  89. if (mgr != null) {
  90. String name = getActiveSessionsCacheName();
  91. cache = mgr.getCache(name);
  92. }
  93. return cache;
  94. }
  95. /**
  96. * AbstractSessionDAO中create的重写
  97. * 调用父类(AbstractSessionDAO)的create方法, 然后将session缓存起来
  98. * 返回sessionId
  99. */
  100. public Serializable create(Session session) {
  101. Serializable sessionId = super.create(session); // 调用父类的create方法
  102. cache(session, sessionId); // 以sessionId作为key缓存session
  103. return sessionId;
  104. }
  105. /**
  106. * 从缓存中获取session; 若sessionId为null,则返回null
  107. */
  108. protected Session getCachedSession(Serializable sessionId) {
  109. Session cached = null;
  110. if (sessionId != null) {
  111. Cache<Serializable, Session> cache = getActiveSessionsCacheLazy();
  112. if (cache != null) {
  113. cached = getCachedSession(sessionId, cache);
  114. }
  115. }
  116. return cached;
  117. }
  118. /**
  119. * 从缓存中获取session
  120. */
  121. protected Session getCachedSession(Serializable sessionId, Cache<Serializable, Session> cache) {
  122. return cache.get(sessionId);
  123. }
  124. /**
  125. * 缓存session,以sessionId作为key
  126. */
  127. protected void cache(Session session, Serializable sessionId) {
  128. if (session == null || sessionId == null) {
  129. return;
  130. }
  131. Cache<Serializable, Session> cache = getActiveSessionsCacheLazy();
  132. if (cache == null) {
  133. return;
  134. }
  135. cache(session, sessionId, cache);
  136. }
  137. protected void cache(Session session, Serializable sessionId, Cache<Serializable, Session> cache) {
  138. cache.put(sessionId, session);
  139. }
  140. /**
  141. * AbstractSessionDAO中readSession的重写
  142. * 先从缓存中获取,若没有则调用父类的readSession方法获取session
  143. */
  144. public Session readSession(Serializable sessionId) throws UnknownSessionException {
  145. Session s = getCachedSession(sessionId); // 从缓存中获取
  146. if (s == null) {
  147. s = super.readSession(sessionId); // 调用父类readSession方法获取
  148. }
  149. return s;
  150. }
  151. /**
  152. * SessionDAO中update的实现
  153. * 更新session的状态
  154. */
  155. public void update(Session session) throws UnknownSessionException {
  156. doUpdate(session); // 更新EIS中的session
  157. if (session instanceof ValidatingSession) {
  158. if (((ValidatingSession) session).isValid()) {
  159. cache(session, session.getId()); // 更新缓存中的session
  160. } else {
  161. uncache(session); // 移除缓存中的sesson
  162. }
  163. } else {
  164. cache(session, session.getId());
  165. }
  166. }
  167. /**
  168. * 由子类去实现,持久化session到EIS
  169. */
  170. protected abstract void doUpdate(Session session);
  171. /**
  172. * SessionDAO中delete的实现
  173. * 删除session
  174. */
  175. public void delete(Session session) {
  176. uncache(session); // 从缓存中移除
  177. doDelete(session); // 从EIS中删除
  178. }
  179. /**
  180. * 由子类去实现,从EIS中删除session
  181. */
  182. protected abstract void doDelete(Session session);
  183. /**
  184. * 从缓存中移除指定的session
  185. */
  186. protected void uncache(Session session) {
  187. if (session == null) {
  188. return;
  189. }
  190. Serializable id = session.getId();
  191. if (id == null) {
  192. return;
  193. }
  194. Cache<Serializable, Session> cache = getActiveSessionsCacheLazy();
  195. if (cache != null) {
  196. cache.remove(id);
  197. }
  198. }
  199. /**
  200. * SessionDAO中getActiveSessions的实现
  201. * 获取所有的存活的session
  202. */
  203. public Collection<Session> getActiveSessions() {
  204. Cache<Serializable, Session> cache = getActiveSessionsCacheLazy();
  205. if (cache != null) {
  206. return cache.values();
  207. } else {
  208. return Collections.emptySet();
  209. }
  210. }
  211. }
View Code

    是应用层与持久化层之间的缓存层,不用频繁请求持久化层以提升效率。重写了AbstractSessionDAO中的create、readSession方法,实现了SessionDAO中的update、delete、getActiveSessions方法,预留doUpdate和doDelele给子类去实现(doXXX方法操作的是持久层)

  MemorySessionDAO,SessionDAO的简单内存实现,如下

  1. package org.apache.shiro.session.mgt.eis;
  2. import org.apache.shiro.session.Session;
  3. import org.apache.shiro.session.UnknownSessionException;
  4. import org.apache.shiro.util.CollectionUtils;
  5. import org.slf4j.Logger;
  6. import org.slf4j.LoggerFactory;
  7. import java.io.Serializable;
  8. import java.util.Collection;
  9. import java.util.Collections;
  10. import java.util.concurrent.ConcurrentHashMap;
  11. import java.util.concurrent.ConcurrentMap;
  12. /**
  13. * 基于内存的SessionDao的简单实现,所有的session存在ConcurrentMap中
  14. * DefaultSessionManager默认用的MemorySessionDAO
  15. */
  16. public class MemorySessionDAO extends AbstractSessionDAO {
  17. private static final Logger log = LoggerFactory.getLogger(MemorySessionDAO.class);
  18. private ConcurrentMap<Serializable, Session> sessions; // 存放session的容器
  19.  
  20. public MemorySessionDAO() {
  21. this.sessions = new ConcurrentHashMap<Serializable, Session>();
  22. }
  23. // AbstractSessionDAO 中doCreate的重写; 将session存入sessions
  24. protected Serializable doCreate(Session session) {
  25. Serializable sessionId = generateSessionId(session); // 生成sessionId
  26. assignSessionId(session, sessionId); // 将sessionId赋值到session
  27. storeSession(sessionId, session); // 存储session到sessions
  28. return sessionId;
  29. }
  30. // 存储session到sessions
  31. protected Session storeSession(Serializable id, Session session) {
  32. if (id == null) {
  33. throw new NullPointerException("id argument cannot be null.");
  34. }
  35. return sessions.putIfAbsent(id, session);
  36. }
  37. // AbstractSessionDAO 中doReadSession的重写; 从sessions中获取session
  38. protected Session doReadSession(Serializable sessionId) {
  39. return sessions.get(sessionId);
  40. }
  41. // SessionDAO中update的实现; 更新sessions中指定的session
  42. public void update(Session session) throws UnknownSessionException {
  43. storeSession(session.getId(), session);
  44. }
  45. // SessionDAO中delete的实现; 从sessions中移除指定的session
  46. public void delete(Session session) {
  47. if (session == null) {
  48. throw new NullPointerException("session argument cannot be null.");
  49. }
  50. Serializable id = session.getId();
  51. if (id != null) {
  52. sessions.remove(id);
  53. }
  54. }
  55. // SessionDAO中SessionDAO中delete的实现的实现; 获取sessions中全部session
  56. public Collection<Session> SessionDAOdelete的实现() {
  57. Collection<Session> values = sessions.values();
  58. if (CollectionUtils.isEmpty(values)) {
  59. return Collections.emptySet();
  60. } else {
  61. return Collections.unmodifiableCollection(values);
  62. }
  63. }
  64. }
View Code

    将session保存在内存中,存储结构是ConcurrentHashMap;项目中基本不用,即使我们不实现自己的SessionDAO,一般用的也是EnterpriseCacheSessionDAO。

  EnterpriseCacheSessionDAO,提供了缓存功能的session维护,如下

  1. package org.apache.shiro.session.mgt.eis;
  2. import org.apache.shiro.cache.AbstractCacheManager;
  3. import org.apache.shiro.cache.Cache;
  4. import org.apache.shiro.cache.CacheException;
  5. import org.apache.shiro.cache.MapCache;
  6. import org.apache.shiro.session.Session;
  7. import java.io.Serializable;
  8. import java.util.concurrent.ConcurrentHashMap;
  9. public class EnterpriseCacheSessionDAO extends CachingSessionDAO {
  10. public EnterpriseCacheSessionDAO() {
  11. // 设置默认缓存器,并实例化MapCache作为cache实例
  12. setCacheManager(new AbstractCacheManager() {
  13. @Override
  14. protected Cache<Serializable, Session> createCache(String name) throws CacheException {
  15. return new MapCache<Serializable, Session>(name, new ConcurrentHashMap<Serializable, Session>());
  16. }
  17. });
  18. }
  19. // AbstractSessionDAO中doCreate的重写;
  20. protected Serializable doCreate(Session session) {
  21. Serializable sessionId = generateSessionId(session);
  22. assignSessionId(session, sessionId);
  23. return sessionId;
  24. }
  25. // AbstractSessionDAO中doReadSession的重写
  26. protected Session doReadSession(Serializable sessionId) {
  27. return null; //should never execute because this implementation relies on parent class to access cache, which
  28. //is where all sessions reside - it is the cache implementation that determines if the
  29. //cache is memory only or disk-persistent, etc.
  30. }
  31. // CachingSessionDAO中doUpdate的重写
  32. protected void doUpdate(Session session) {
  33. //does nothing - parent class persists to cache.
  34. }
  35. // CachingSessionDAO中doDelete的重写
  36. protected void doDelete(Session session) {
  37. //does nothing - parent class removes from cache.
  38. }
  39. }
View Code

    设置了默认的缓存管理器(AbstractCacheManager)和默认的缓存实例(MapCache),实现了缓存效果。从父类继承的持久化操作方法(doXXX)都是空实现,也就说EnterpriseCacheSessionDAO是没有实现持久化操作的,仅仅只是简单的提供了缓存实现。当然我们可以继承EnterpriseCacheSessionDAO,重写doXXX方法来实现持久化操作。

  总结下:SessionDAO定义了从持久层操作session的标准;AbstractSessionDAO提供了SessionDAO的基础实现,如生成会话ID等;CachingSessionDAO提供了对开发者透明的session缓存的功能,只需要设置相应的 CacheManager 即可;MemorySessionDAO直接在内存中进行session维护;而EnterpriseCacheSessionDAO提供了缓存功能的session维护,默认情况下使用 MapCache 实现,内部使用ConcurrentHashMap保存缓存的会话。因为shiro不知道我们需要将session持久化到哪里(关系型数据库,还是文件系统),所以只提供了MemorySessionDAO持久化到内存(听起来怪怪的,内存中能说成持久层吗)

shiro session共享

  共享实现

    shiro的session共享其实是比较简单的,重写CacheManager,将其操作指向我们的redis,然后实现我们自己的CachingSessionDAO定制缓存操作和缓存持久化。

    自定义CacheManager

      ShiroRedisCacheManager

  1. package com.lee.shiro.config;
  2. import org.apache.shiro.cache.Cache;
  3. import org.apache.shiro.cache.CacheException;
  4. import org.apache.shiro.cache.CacheManager;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.stereotype.Component;
  7. @Component
  8. public class ShiroRedisCacheManager implements CacheManager {
  9. @Autowired
  10. private Cache shiroRedisCache;
  11. @Override
  12. public <K, V> Cache<K, V> getCache(String s) throws CacheException {
  13. return shiroRedisCache;
  14. }
  15. }
View Code

      ShiroRedisCache

  1. package com.lee.shiro.config;
  2. import org.apache.shiro.cache.Cache;
  3. import org.apache.shiro.cache.CacheException;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.beans.factory.annotation.Value;
  6. import org.springframework.data.redis.core.RedisTemplate;
  7. import org.springframework.stereotype.Component;
  8. import java.util.Collection;
  9. import java.util.Set;
  10. import java.util.concurrent.TimeUnit;
  11. @Component
  12. public class ShiroRedisCache<K,V> implements Cache<K,V>{
  13. @Autowired
  14. private RedisTemplate<K,V> redisTemplate;
  15. @Value("${spring.redis.expireTime}")
  16. private long expireTime;
  17. @Override
  18. public V get(K k) throws CacheException {
  19. return redisTemplate.opsForValue().get(k);
  20. }
  21. @Override
  22. public V put(K k, V v) throws CacheException {
  23. redisTemplate.opsForValue().set(k,v,expireTime, TimeUnit.SECONDS);
  24. return null;
  25. }
  26. @Override
  27. public V remove(K k) throws CacheException {
  28. V v = redisTemplate.opsForValue().get(k);
  29. redisTemplate.opsForValue().getOperations().delete(k);
  30. return v;
  31. }
  32. @Override
  33. public void clear() throws CacheException {
  34. }
  35. @Override
  36. public int size() {
  37. return 0;
  38. }
  39. @Override
  40. public Set<K> keys() {
  41. return null;
  42. }
  43. @Override
  44. public Collection<V> values() {
  45. return null;
  46. }
  47. }
View Code

    自定义CachingSessionDAO

      继承EnterpriseCacheSessionDAO,然后重新设置其CacheManager(替换掉默认的内存缓存器),这样也可以实现我们的自定义CachingSessionDAO,但是这是优选吗;如若我们实现持久化,继承EnterpriseCacheSessionDAO是优选,但如果只是实现session缓存,那么CachingSessionDAO是优选,自定义更灵活。那么我们还是继承CachingSessionDAO来实现我们的自定义CachingSessionDAO

      ShiroSessionDAO

  1. package com.lee.shiro.config;
  2. import org.apache.shiro.session.Session;
  3. import org.apache.shiro.session.mgt.eis.CachingSessionDAO;
  4. import org.springframework.stereotype.Component;
  5. import java.io.Serializable;
  6. @Component
  7. public class ShiroSessionDAO extends CachingSessionDAO {
  8. @Override
  9. protected void doUpdate(Session session) {
  10. }
  11. @Override
  12. protected void doDelete(Session session) {
  13. }
  14. @Override
  15. protected Serializable doCreate(Session session) {
  16. // 这里绑定sessionId到session,必须要有
  17. Serializable sessionId = generateSessionId(session);
  18. assignSessionId(session, sessionId);
  19. return sessionId;
  20. }
  21. @Override
  22. protected Session doReadSession(Serializable sessionId) {
  23. return null;
  24. }
  25. }
View Code

    最后将ShiroSessionDAO实例赋值给SessionManager实例,再讲SessionManager实例赋值给SecurityManager实例即可

    具体代码请参考spring-boot-shiro

  源码解析

    底层还是利用Filter + HttpServletRequestWrapper将对session的操作接入到自己的实现中来,而不走默认的servlet容器,这样对session的操作完全由我们自己掌握。

    shiro的session创建中其实讲到了shiro中对session操作的基本流程,这里不再赘述,没看的朋友可以先去看看再回过头来看这篇。本文只讲shiro中,如何将一个请求的session接入到自己的实现中来的;shiro中有很多默认的filter,我会单独开一篇来讲shiro的filter,这篇我们先不纠结这些filter。

    OncePerRequestFilter中doFilter方法如下

  1. public final void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
  2. throws ServletException, IOException {
  3. String alreadyFilteredAttributeName = getAlreadyFilteredAttributeName();
  4. if ( request.getAttribute(alreadyFilteredAttributeName) != null ) { // 当前filter已经执行过了,进行下一个filter
  5. log.trace("Filter '{}' already executed. Proceeding without invoking this filter.", getName());
  6. filterChain.doFilter(request, response);
  7. } else //noinspection deprecation
  8. if (/* added in 1.2: */ !isEnabled(request, response) ||
  9. /* retain backwards compatibility: */ shouldNotFilter(request) ) { // 当前filter未被启用或忽略此filter,则进行下一个filter;shouldNotFilter已经被废弃了
  10. log.debug("Filter '{}' is not enabled for the current request. Proceeding without invoking this filter.",
  11. getName());
  12. filterChain.doFilter(request, response);
  13. } else {
  14. // Do invoke this filter...
  15. log.trace("Filter '{}' not yet executed. Executing now.", getName());
  16. request.setAttribute(alreadyFilteredAttributeName, Boolean.TRUE);
  17. try {
  18. // 执行当前filter
  19. doFilterInternal(request, response, filterChain);
  20. } finally {
  21. // 一旦请求完成,我们清除当前filter的"已经过滤"的状态
  22. request.removeAttribute(alreadyFilteredAttributeName);
  23. }
  24. }
  25. }
View Code

    上图中,我可以看到AbstractShiroFilter的doFilterInternal放中将request封装成了shiro自定义的ShiroHttpServletRequest,将response也封装成了shiro自定义的ShiroHttpServletResponse。既然Filter中将request封装了ShiroHttpServletRequest,那么到我们应用的request就是ShiroHttpServletRequest类型,也就是说我们对session的操作最终都是由shiro完成的,而不是默认的servlet容器。

    另外补充一点,shiro的session创建不是懒创建的。servlet容器中的session创建是第一次请求session(第一调用request.getSession())时才创建。shiro的session创建如下图

    此时,还没登录,但是subject、session已经创建了,只是subject的认证状态为false,说明还没进行登录认证的。至于session创建过程已经保存到redis的流程需要大家自行去跟,或者阅读我之前的博文

总结

  1、当以集群方式对外提供服务的时候,不做session共享也是可以的

    可以通过ip_hash的机制将同个ip的请求定向到同一台后端,这样保证用户的请求始终是同一台服务处理,与单机应用基本一致了;但这有很多方面的缺陷(具体就不详说了),不推荐使用。

  2、servlet容器之间做session同步也是可以实现session共享的

    一个servlet容器生成session,其他节点的servlet容器从此servlet容器进行session同步,以达到session信息一致。这个也不推荐,某个时间点会有session不一致的问题,毕竟同步过程受到各方面的影响,不能保证session实时一致。

  3、session共享实现的原理其实都是一样的,都是filter + HttpServletRequestWrapper,只是实现细节会有所区别;有兴趣的可以看下spring-session的实现细节。

  4、如果我们采用的spring集成shiro,其实可以将缓存管理器交由spring管理,相当于由spring统一管理缓存。

  5、shiro的CacheManager不只是管理session缓存,还管理着身份认证缓存、授权缓存,shiro的缓存都是CacheManager管理。但是身份认证缓存默认是关闭的,个人也不推荐开启。

  6、shiro的session创建时机是在登录认证之前,而不是第一次调用getSession()时。

参考

  《跟我学shiro》

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号