Spring boot integrates redis to implement shiro distributed session sharing, redisshiro

Source: Internet
Author: User

Spring boot integrates redis to implement shiro distributed session sharing, redisshiro

We know that shiro manages sessions through SessionManager, while Session operations are implemented through SessionDao. By default, shiro implements two kinds of SessionDao, the two are CachingSessionDAO and MemorySessionDAO. When we use the EhCache cache, The CachingSessionDAO is used. If the cache is not applicable, the memory-based SessionDao is selected. therefore, if we want to implement Redis-based distributed Session sharing, we will focus on Rewriting SessionDao in SessionManager. The rewrite code is as follows:

Package com. chhliu. springboot. shiro. cache; import java. io. serializable; import java. util. collection; import java. util. concurrent. timeUnit; import org. apache. shiro. session. session; import org. apache. shiro. session. unknownSessionException; import org. apache. shiro. session. mgt. eis. abstractSessionDAO; import org. springframework. beans. factory. annotation. autowired; import org. springframework. data. redis. core. redisTemplate; import org. springframework. stereotype. service; @ Service @ SuppressWarnings ({"rawtypes", "unchecked"}) public class RedisSessionDao extends actsessiondao {// Session Timeout time, in milliseconds private long expireTime = 120000; @ Autowired private RedisTemplate redisTemplate; // Redis operation class. If you are not familiar with this operation, refer to the previous blog public RedisSessionDao () {super ();} public RedisSessionDao (long expireTime, redisTemplate redisTemplate) {super (); this. expireTime = expireTime; this. redisTemplate = redisTemplate;} @ Override // update session public void update (Session session) throws UnknownSessionException {System. out. println ("==================== update ========================== "); if (session = null | session. getId () = null) {return;} session. setTimeout (expireTime); redisTemplate. opsForValue (). set (session. getId (), session, expireTime, TimeUnit. MILLISECONDS) ;}@ Override // delete session public void delete (Session session) {System. out. println ("===================== delete ========================= "); if (null = session) {return;} redisTemplate. opsForValue (). getOperations (). delete (session. getId () ;}@ Override // gets an Active session, which can be used to count the number of online users. To implement this function, you can specify a session prefix when adding a session to redis, during statistics, keys ("session-prefix *") is used to fuzzy search for all session sets in redis public Collection <Session> getActiveSessions () {System. out. println ("================= getActiveSessions ============================ "); return redisTemplate. keys ("*") ;}@ Override // Add session protected Serializable doCreate (Session session) {System. out. println ("==================== doCreate ======================== "); serializable sessionId = this. generateSessionId (session); this. assignSessionId (session, sessionId); redisTemplate. opsForValue (). set (session. getId (), session, expireTime, TimeUnit. MILLISECONDS); return sessionId;} @ Override // read session protected Session doReadSession (Serializable sessionId) {System. out. println ("================== doReadSession ============================ "); if (sessionId = null) {return null;} return (Session) redisTemplate. opsForValue (). get (sessionId);} public long getExpireTime () {return expireTime;} public void setExpireTime (long expireTime) {this. expireTime = expireTime;} public RedisTemplate getRedisTemplate () {return redisTemplate;} public void setRedisTemplate (RedisTemplate redisTemplate) {this. redisTemplate = redisTemplate ;}}

After implementing SessionDao, we need to add SessionDao to SessionManager. The Code is as follows:

@ Bean public defawebwebsessionmanager configWebSessionManager () {defawebwebsessionmanager manager = new DefaultWebSessionManager (); manager. setCacheManager (cacheManager); // Add it to the cache manager. setSessionDAO (sessionDao); // sets SessionDao manager. setdeletvalvalidsessions (true); // Delete the expired session manager. setGlobalSessionTimeout (sessionDao. getExpireTime (); // sets the global session Timeout manager. setSessionValidationSchedulerEnabled (true); // check whether the session return manager is scheduled ;}

The last step is to configure SessionManager to SecurityManager.

@ Bean public SecurityManager securityManager (DefaultWebSessionManager webSessionManager) {defawebwebsecuritymanager securityManager = new DefaultWebSecurityManager (); // set realm. securityManager. setRealm (myShiroRealm (); // inject cache manager; securityManager. setCacheManager (cacheManager); // This is the same object if it is executed multiple times; // session Manager securityManager. setSessionManager (webSessionManager); // inject my account manager; securityManager. setRememberMeManager (rememberMeManager (); return securityManager ;}

The test results are as follows:

=============== DoReadSession ==================================
=============== DoReadSession ==================================
=============== DoReadSession ==================================
=============== DoReadSession ==================================
=============== DoReadSession ==================================
=============== DoReadSession ==================================
=============== DoReadSession ==================================
=============== DoReadSession ==================================
=============== DoReadSession ==================================
=============== DoReadSession ==================================
=============== DoReadSession ==================================
=============== DoReadSession ==================================
================== Update ==============================
=============== DoReadSession ==================================
=============== DoReadSession ==================================
================== Update ==============================
=============== DoReadSession ==================================
=============== DoReadSession ==================================
=============== DoReadSession ==================================
Permission configuration --> MyShiroRealm. doGetAuthorizationInfo ()
=============== DoReadSession ==================================

We will find that when multiple resources exist in a page, we will constantly call the doReadSession and update method to read and update sessions. At present, we have not yet come up with a better solution to this problem.

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.