shiro-redis實現session存儲到redis

  shiro-redis開源項目已經很好的將shiro與redis整合到一塊兒,實現了將session存入redis,能夠方便的用於session共享實現集羣部署。css

  git地址:https://github.com/alexxiyang/shiro-redis ,文檔:http://alexxiyang.github.io/shiro-redis/java

  官方的文檔已經很是詳細了,基本上照着文檔進行修改原來的配置就能夠了。git

1.在原生的shiro基礎上新增的jar包:

commons-pool2-2.6.1.jar
jedis-2.9.0.jar
shiro-redis-3.2.2.jargithub

2.修改配置: 

下面是參考的配置,將對應的bean以及依賴關係修改成下面的配置便可web

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
 http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context 
 http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/aop 
 http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/tx 
 http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">

    <!-- shiro-redis configuration [start] -->

    <!-- Redis Manager [start] -->
    <bean id="redisManager" class="org.crazycake.shiro.RedisManager">
        <property name="host" value="127.0.0.1:6379" />
    </bean>
    <!-- Redis Manager [end] -->

    <!-- Redis session DAO [start] -->
    <bean id="redisSessionDAO" class="org.crazycake.shiro.RedisSessionDAO">
        <property name="redisManager" ref="redisManager" />
    </bean>
    <bean id="sessionManager"
        class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager">
        <property name="sessionDAO" ref="redisSessionDAO" />
    </bean>
    <!-- Redis session DAO [end] -->

    <!-- Redis cache manager [start] -->
    <bean id="cacheManager" class="org.crazycake.shiro.RedisCacheManager">
        <property name="redisManager" ref="redisManager" />
    </bean>
    <!-- Redis cache manager [end] -->

    <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
        <property name="sessionManager" ref="sessionManager" />
        <property name="cacheManager" ref="cacheManager" />

        <!-- other configurations -->
        <property name="realm" ref="exampleRealm" />
        <property name="rememberMeManager.cipherKey" value="kPH+bIxk5D2deZiIxcaaaA==" />
    </bean>

    <!-- shiro-redis configuration [end] -->
</beans>  

 

 

 須要注意:redis

  1.存入session的信息要實現Serializable接口(包括其依賴的成員屬性等bean也要實現)spring

  2.對存入session的bean要有個惟一標識,且要設值到cacheManager,好比:apache

package cn.xm.exam.bean.system;

import java.io.Serializable;
import java.util.Date;
import java.util.List;


public class User implements Serializable{
    /**
     * 
     */
    private static final long serialVersionUID = -3207880482640325843L;

    private String userid;

    private String useridcard;

    private String password;

    private String username;

    private String departmentname;
    
    private String departmentid;

    private String employeeid;

    private String userphoto;
    
    
    private String phone;
    

    private String isuse;
    
    private Date datatime;
    
    private Date logintime;
    private List<Role> roles; //用戶所擁有的角色
    
    private List<String> permissions;//用戶所擁有的權限code集合
    
    
    public List<Role> getRoles() {
        return roles;
    }

    public void setRoles(List<Role> roles) {
        this.roles = roles;
    }
    

    public String getUserid() {
        return userid;
    }

    public void setUserid(String userid) {
        this.userid = userid == null ? null : userid.trim();
    }

    public String getUseridcard() {
        return useridcard;
    }

    public void setUseridcard(String useridcard) {
        this.useridcard = useridcard == null ? null : useridcard.trim();
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password == null ? null : password.trim();
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username == null ? null : username.trim();
    }

    public String getDepartmentname() {
        return departmentname;
    }

    public void setDepartmentname(String departmentname) {
        this.departmentname = departmentname == null ? null : departmentname.trim();
    }

    public String getEmployeeid() {
        return employeeid;
    }

    public void setEmployeeid(String employeeid) {
        this.employeeid = employeeid == null ? null : employeeid.trim();
    }

    public String getUserphoto() {
        return userphoto;
    }

    public void setUserphoto(String userphoto) {
        this.userphoto = userphoto == null ? null : userphoto.trim();
    }

    public String getIsuse() {
        return isuse;
    }

    public void setIsuse(String isuse) {
        this.isuse = isuse == null ? null : isuse.trim();
    }

    public String getDepartmentid() {
        return departmentid;
    }

    public void setDepartmentid(String departmentid) {
        this.departmentid = departmentid;
    }


    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public List<String> getPermissions() {
        return permissions;
    }

    public void setPermissions(List<String> permissions) {
        this.permissions = permissions;
    }

    public Date getDatatime() {
        return datatime;
    }

    public void setDatatime(Date datatime) {
        this.datatime = datatime;
    }

    public Date getLogintime() {
        return logintime;
    }

    public void setLogintime(Date logintime) {
        this.logintime = logintime;
    }
    
}

 

在配置cacheManager的時候以下:緩存

    <!-- Redis cache manager [start] -->
    <bean id="cacheManager" class="org.crazycake.shiro.RedisCacheManager">
        <property name="redisManager" ref="redisManager" />
        <!-- shiro-redis will call userInfo.getUserid() to get the id for storing Redis object.  -->
        <property name="principalIdFieldName" value="userid" />
    </bean>
    <!-- Redis cache manager [end] -->

 

最終個人完整的shiro相關配置:安全

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
 http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context 
 http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/aop 
 http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/tx 
 http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">

    <!-- Redis Manager [start] -->
    <bean id="redisManager" class="org.crazycake.shiro.RedisManager">
        <property name="host" value="127.0.0.1:6379" />
    </bean>
    <!-- Redis Manager [end] -->

    <!-- Redis session DAO [start] -->
    <bean id="redisSessionDAO" class="org.crazycake.shiro.RedisSessionDAO">
        <property name="redisManager" ref="redisManager" />
    </bean>

    <!-- Redis cache manager [start] -->
    <bean id="cacheManager" class="org.crazycake.shiro.RedisCacheManager">
        <property name="redisManager" ref="redisManager" />
        <!-- shiro-redis will call userInfo.getUserid() to get the id for storing Redis object.  -->
        <property name="principalIdFieldName" value="userid" />
    </bean>
    <!-- Redis cache manager [end] -->

    <!-- 安全管理器 -->
    <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
        <property name="realm" ref="myRealm" />
        <!-- 記住我 -->
        <property name="rememberMeManager" ref="rememberMeManager" />
        <!-- 注入緩存管理器 -->
        <property name="cacheManager" ref="cacheManager" />
        <!-- 注入session管理器 -->
        <property name="sessionManager" ref="sessionManager" />
    </bean>

    <!-- 自定義Realm -->
    <bean id="myRealm" class="cn.xm.exam.utils.realm.MyRealm" />

    <!-- 自定義form認證過慮器 -->
    <!-- 基於Form表單的身份驗證過濾器,不配置將也會註冊此過慮器,表單中的用戶帳號、密碼及loginurl將採用默認值,建議配置 -->
    <bean id="formAuthenticationFilter"
        class="org.apache.shiro.web.filter.authc.FormAuthenticationFilter ">

        <property name="usernameParam" value="username" />

        <property name="passwordParam" value="password" />

        <property name="rememberMeParam" value="rememberMe" />
    </bean>

    <!-- ehcache緩存管理器 -->
    <bean id="cacheManager222" class="org.apache.shiro.cache.ehcache.EhCacheManager">
        <property name="cacheManagerConfigFile" value="classpath:shiro-ehcache.xml" />
    </bean>

    <!-- session會話管理器 -->
    <bean id="sessionManager"
        class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager">
        <!-- session失效時間 單位毫秒 -->
        <property name="globalSessionTimeout" value="18000000" />
        <!-- 刪除失效的session -->
        <property name="deleteInvalidSessions" value="true" />

        <property name="sessionDAO" ref="redisSessionDAO" />
    </bean>

    <!-- rememberMeManager管理器,寫cookie,取出cookie生成用戶信息 -->
    <bean id="rememberMeManager" class="org.apache.shiro.web.mgt.CookieRememberMeManager">
        <property name="cookie" ref="rememberMeCookie" />
    </bean>
    <!-- 會話Cookie模板 -->
    <bean id="sessionIdCookie" class="org.apache.shiro.web.servlet.SimpleCookie">
        <constructor-arg value="sid" />
        <property name="httpOnly" value="true" />
        <property name="maxAge" value="-1" />
    </bean>
    <bean id="rememberMeCookie" class="org.apache.shiro.web.servlet.SimpleCookie">
        <constructor-arg value="rememberMe" />
        <property name="httpOnly" value="true" />
        <property name="maxAge" value="2592000" /><!-- 30天 -->
    </bean>

    <!-- 自定義form認證過慮器 -->
    <bean id="permfilter" class="cn.xm.exam.utils.realm.ShiroPermsFilter"
        scope="prototype">
    </bean>

    <!-- logout -->
    <bean id="logoutFilter" class="org.apache.shiro.web.filter.authc.LogoutFilter">
        <!-- <property name="redirectUrl" value="/index.jsp" /> -->
        <property name="redirectUrl" value="/view/index/studyMainpage2.jsp" />
    </bean>

    <!-- shiro 過濾器 -->
    <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
        <property name="securityManager" ref="securityManager" />
        <!-- loginUrl認證提交地址,若是沒有認證將會請求此地址進行認證,請求此地址將由formAuthenticationFilter進行表單認證 -->
        <!-- <property name="loginUrl" value="/index.jsp" /> --> 
        <property name="loginUrl" value="/view/index/studyMainpage2.jsp" />
        <!-- 認證成功統一跳轉到first.action,建議不配置,shiro認證成功自動到上一個請求路徑 -->
        <!--  <property name="successUrl" value="/login"/>  -->
        <!-- 經過unauthorizedUrl指定沒有權限操做時跳轉頁面-->
        <property name="unauthorizedUrl" value="unauthorized.jsp" /> 
        
           <property name="filters">
            <map>
                <entry key="logout" value-ref="logoutFilter" />
            </map>
        </property>
        
        <!-- 過慮器鏈定義,從上向下順序執行,通常將/**放在最下邊 -->
        <property name="filterChainDefinitions">
            <value>
                <!-- 對靜態資源設置匿名訪問 -->
                / = anon <!-- 不攔截首頁的地址 -->
                /index.jsp = anon
                /WS/** = anon
                /newsIP_**.action = anon
                /train_**.action = anon
                /dic_***.action = anon
                /unauthorized.jsp = anon
                /user_login.action = anon
                /view/public/** = anon
                /view/index/** = anon
                /bs/** = anon
                /controls/** = anon
                /css/** = anon
                /image/** = anon
                /js/** = anon
                /META-INF/** = anon

                <!-- 請求 logout.action地址,shiro去清除session-->
                /logout.action = logout
                
                <!-- /** = authc 全部url都必須認證經過才能夠訪問-->
                /** = authc
                    
            </value>
        </property>
    </bean>

    <!-- 開啓Shiro註解 -->
    <!-- <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" 
        depends-on="lifecycleBeanPostProcessor"> <property name="proxyTargetClass" 
        value="true"></property> </bean> <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor"> 
        <property name="securityManager" ref="securityManager"/> </bean> -->

    <aop:config proxy-target-class="true"></aop:config>
    <bean
        class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
        <property name="securityManager" ref="securityManager" />
    </bean>

    <!-- 保證明現了Shiro內部lifecycle函數的bean執行 -->
    <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor" />
</beans>  

 

  接下來正常訪問便可。session的修改以及清空都交給redis便可。咱們手動清空redis以後至關於清除全部session。會將咱們的信息都存入redis:

 

  對於集羣的redis也都有相關介紹,對於哨兵模式的集羣和主從複製的集羣都有相關配置,須要的時候查閱文檔就能夠了。

個人項目的git地址:https://github.com/qiao-zhi/Exam/tree/sessionRedis

相關文章
相關標籤/搜索