Spring+shiro+redis implementation session Sharing __spring+redis

Source: Internet
Author: User
Tags getmessage redis

Using spring's redistemplate to implement session access, first configure the Applicationcontext-shiro.xml

<!--Session Manager--> <bean id= "SessionManager class=" Org.apache.shiro.web.session.mgt.DefaultWebSessionM 
        Anager "> <property name=" sessionvalidationinterval "value=" 1800000 "/> <!--how often to check the validity of a session--> <property name= "Globalsessiontimeout" value= "1800000"/> <property name= "Deleteinvalidsessions" V Alue= "true"/> <property name= "sessionvalidationschedulerenabled" value= "true"/><!--timed check failed session--&
        Gt <!--<property name= "Sessionvalidationscheduler" ref= "Sessionvalidationscheduler"/>--> <property Nam
        E= "Sessiondao" ref= "Sessiondao"/> <!--<property name= "Sessionidcookie" ref= "Simplecookie"/>--> <property name= "Sessionidcookie.name" value= "shiro.sesssion"/> <property name= "SessionIdCookie.path" Value= "/"/> <property name= "sessionidcookieenabled" value= "true"/> <!--<property name= "Sess Ionidcookie " ref= "Sessionidcookie"/>--> </bean> <!--session DAO--> <bean id= "Sessiondao" class= "Com.ogma" Ll.web.manager.cache.RedisSessionDao "> <property name=" redistemplate "ref=" Redisobjecttemplate "></pro" perty> </bean> <bean id= "redisobjecttemplate" class= "Org.springframework.data.redis.core.RedisTemplate" "> <property name=" connectionfactory "ref=" Jedisconnectionfactory "/> <!--If you do not configure serializer, the stored  String is used by default, and if stored with the user type, the error user can ' t cast to String is prompted. --> <property name= "Keyserializer" > <bean class= "Org.springframework.data.redis.serializer .  Stringredisserializer "/> </property> <property name=" ValueSerializer "> <bean
        class= "Org.springframework.data.redis.serializer.JdkSerializationRedisSerializer"/> </property> <property name= "Hashkeyserializer" > <bean class= "org.springframework". Data.redis.serializer.StringRedisSerializer "/> </property> <property name=" hashvalueserialize
        R "> <bean class=" Org.springframework.data.redis.serializer.JdkSerializationRedisSerializer "/>
        </property> </bean> <bean id= "Jedispoolconfig" class= "Redis.clients.jedis.JedisPoolConfig" > <property name= "Maxtotal" value= "></property> <property" name= "Maxidle" value= "></pro" perty> <property name= "Minidle" value= "ten" ></property> <property name= "Maxwaitmillis" va Lue= "<property" ></property> name= "Testonborrow" value= "true" ></property> &LT;PR Operty name= "Testonreturn" value= "true" ></property> </bean> <bean id= "Jedisconnectionfactory" cl ass= "Org.springframework.data.redis.connection.jedis.JedisConnectionFactory" > <property name= "HostName" Val
 Ue= "192.168.1.149"/>       <property name= "Port" value= "6379"/> <property name= "poolconfig" ref= "Jedispoolconfig" ></pro perty> <!--<property name= "Timeout" value= "5000" ></property>--> <property name= "us Epool "value= true" ></property> <!--<property name= "password" value= ""/>--> <prop Erty name= "Database" value= "ten"/> </bean>
Redissessiondao.java

Package Com.ogmall.web.manager.cache;
Import org.apache.shiro.session.Session;
Import org.apache.shiro.session.UnknownSessionException;
Import Org.apache.shiro.session.mgt.eis.AbstractSessionDAO;
Import Org.slf4j.Logger;
Import Org.slf4j.LoggerFactory;

Import Org.springframework.data.redis.core.RedisTemplate;
Import java.io.Serializable;
Import java.util.Collection;
Import java.util.Collections;

Import Java.util.concurrent.TimeUnit;
 /** * Created by the Administrator on 2017/6/30 0030.

    * * public class Redissessiondao extends Abstractsessiondao {private redistemplate redistemplate;
    Logger log= Loggerfactory.getlogger (GetClass ());
    /** * The Redis key prefix for the sessions/private String Keyprefix = "Shiro_redis_session_manager:";
    private string Getkey (string originalkey) {return keyprefix+originalkey; @Override public void Update throws Unknownsessionexception {//Log.info ("Update seesion,id= [{}] ', session.geTId (). toString ());
        try {redistemplate.opsforvalue (). Set (Getkey (Session.getid (). toString ()), session,30, timeunit.minutes);
        catch (Exception e) {log.error (E.getmessage (), E); The @Override public void Delete (session session) {Log.info ("delete seesion,id=[{}]", Session.getid (). tostr
        ing ());
            try {String Key=getkey (Session.getid (). toString ());
        Redistemplate.delete (key);
        catch (Exception e) {e.printstacktrace ();        } @Override Public collection<session> getactivesessions () {log.info ("Get Alive Session");//
        System.out.println (Redistemplate.opsforvalue (). Get ("shiro_redis_session_manager:*"));
    return Collections.emptyset (); } @Override protected Serializable Docreate (Session session) {Serializable sessionId = Generatesessionid
        (session);
        Assignsessionid (session, SESSIONID); Log.info ("Create seesion, id=[{}] ", Session.getid (). toString ());
        try {redistemplate.opsforvalue (). Set (Getkey (Session.getid (). toString ()), session,30,timeunit.minutes);
        catch (Exception e) {log.error (E.getmessage ());
    return sessionId; @Override protected Session doreadsession (Serializable sessionId) {//Log.info ("Get seesion,id=[{}]", Sess
        Ionid.tostring ());
        Session session = NULL; try {session= (session) Redistemplate.opsforvalue (). Get (Getkey (sessionid.tostring ()));//System.ou T.println (System.currenttimemillis () + "-" +session.getlastaccesstime (). GetTime () + "=" + (System.currenttimemillis ()
-Session.getlastaccesstime (). GetTime ());                if ((System.currenttimemillis ()-Session.getlastaccesstime (). GetTime ()) >1800000l) {//30 minutes No login expired//
System.out.println ("delete");
Delete (session);
return null;
 } catch (Exception e) {           Log.error (E.getmessage ());
    return to session;
    Public Redistemplate Getredistemplate () {return redistemplate;
    public void Setredistemplate (Redistemplate redistemplate) {this.redistemplate = redistemplate;
 }
}



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.