Spring+Shiro搭建基於Redis的分佈式權限系統(有實例)

摘要: 簡單介紹使用Spring+Shiro搭建基於Redis的分佈式權限系統。css

這篇主要介紹Shiro如何與redis結合搭建分佈式權限系統,至於如何使用和配置Shiro就很少說了。完整實例下載地址:https://git.oschina.net/zhmlvft/spring_shiro_redishtml

要實現分佈式,主要須要解決2個大問題。html5

第一個解決shiro  session共享的問題。這個能夠經過自定義sessionDao實現。繼承 CachingSessionDao。git

public class RedisSessionDao extends CachingSessionDAO {
    private final static Logger log = LoggerFactory.getLogger(RedisSessionDao.class);

    private RedisTemplate<String, Object> redisTemplate;
    private int defaultExpireTime = 3600;

    private CacheManager cm=null;

    public RedisSessionDao(RedisTemplate<String, Object> redisTemplate,int defaultExpireTime) {
        this.redisTemplate = redisTemplate;
        this.defaultExpireTime = defaultExpireTime;
    }

    @Override
    protected Serializable doCreate(Session session) {
        Serializable sessionId = generateSessionId(session);
        cm = CacheManager.create();
        if(cm==null){
            cm = new CacheManager(getCacheManagerConfigFileInputStream());
        }
        Ehcache ehCache = cm.getCache("sessioncache");
        assignSessionId(session, sessionId);
        redisTemplate.opsForValue().set(sessionId.toString(), session);
        redisTemplate.expire(sessionId.toString(), this.defaultExpireTime, TimeUnit.SECONDS);
        ehCache.put(new Element(sessionId.toString(),session));
        return sessionId;
    }

    @Override
    protected Session doReadSession(Serializable sessionId) {
        //此方法不會執行,不用管
        return null;
    }

    @Override
    protected void doUpdate(Session session) {
        //該方法交給父類去執行
    }


    @Override
    protected void doDelete(Session session) {

        Serializable sessionId = session.getId();
        cm = CacheManager.create();
        if(cm==null){
            cm = new CacheManager(getCacheManagerConfigFileInputStream());
        }
        Ehcache ehCache = cm.getCache("sessioncache");
        redisTemplate.delete(sessionId.toString());
        ehCache.remove(sessionId.toString());
    }

    protected InputStream getCacheManagerConfigFileInputStream() {
        String configFile = "classpath:ehcache.xml";
        try {
            return ResourceUtils.getInputStreamForPath(configFile);
        } catch (IOException e) {
            throw new ConfigurationException("Unable to obtain input stream for cacheManagerConfigFile [" +
                    configFile + "]", e);
        }
    }

 

第二個解決shiro cache的問題,這個能夠經過自定義CacheManager實現,shiro默認的cache是基於ehcache的,自定義Redis實現的過程能夠仿照shiro-ehcache.jar源碼來實現。web

附上spring中的完整配置以下:redis

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:jaxws="http://cxf.apache.org/jaxws"
       xmlns:util="http://www.springframework.org/schema/util"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:task="http://www.springframework.org/schema/task"
       xmlns:jee="http://www.springframework.org/schema/jee"
       xmlns:c="http://www.springframework.org/schema/c"
       xmlns:cache="http://www.springframework.org/schema/cache"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-4.1.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
        http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
          http://www.springframework.org/schema/aop
          http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
        http://www.springframework.org/schema/task
          http://www.springframework.org/schema/task/spring-task-4.1.xsd
          http://www.springframework.org/schema/jee
          http://www.springframework.org/schema/jee/spring-jee-4.1.xsd
          http://www.springframework.org/schema/cache
          http://www.springframework.org/schema/cache/spring-cache.xsd">
        <context:annotation-config/>
        <context:component-scan base-package="com.zhm.ssr"/>
        <bean id="propertyConfigurer"
          class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
            <property name="ignoreUnresolvablePlaceholders" value="true" />
            <property name="locations">
                <list>
                    <value>classpath:jdbc.properties</value>
                    <value>classpath:redis.properties</value>
                </list>
            </property>
        </bean>
        <aop:aspectj-autoproxy />
       <!-- spring 線程池配置  -->
        <task:annotation-driven executor="executorWithCallerRunsPolicy"/>
        <task:executor id="executorWithCallerRunsPolicy" pool-size="2-5"  queue-capacity="50"  rejection-policy="CALLER_RUNS"/>
         
        <!-- redis緩存 -->
        <bean id="cacheManager" class="org.springframework.data.redis.cache.RedisCacheManager" c:template-ref="redisTemplate">
            <property name="defaultExpiration" value="31536000"></property>
        </bean>
        <!--  支持註解緩存 -->
        <cache:annotation-driven cache-manager="cacheManager"/>

        <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"/>

        <!-- 文件上傳大小限制 -->
        <bean id="multipartResolver"     class="org.springframework.web.multipart.commons.CommonsMultipartResolver">  
            <property name="maxUploadSize">
                <value>4097152000</value>  
              </property>
        </bean>

        <!--  ========shiro 配置開始 ======== -->
        <bean id="myRealm" class="com.zhm.ssr.shiro.CustomRealm">
            <!-- 配置AuthorizationInfo信息不用放redis緩存,直接放session便可 -->
            <property name="cachingEnabled" value="false"/>
            <property name="authenticationCachingEnabled" value="false" />
        </bean>
        <!-- session 保存到cookie,關閉瀏覽器下次能夠直接登陸認證,當maxAge爲-1不會寫cookie。-->
        <bean id="sessionIdCookie" class="org.apache.shiro.web.servlet.SimpleCookie">
            <constructor-arg value="sid"/>
            <property name="httpOnly" value="true"/>
            <!-- 瀏覽器關閉session失效,不計入cookie -->
            <property name="maxAge" value="-1"/>
        </bean>
        <!--  記住我功能,當關閉瀏覽器下次再訪問的時候不須要登陸也能查看。只對filterChainDefinitions設置爲user級別的連接有效,
             相似於淘寶看商品、添加購物車,不須要驗證是否登陸。可是提交訂單就必須登陸。
        -->
        <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>
        <bean id="rememberMeManager" class="org.apache.shiro.web.mgt.CookieRememberMeManager">
            <property name="cookie" ref="rememberMeCookie"/>
            <!-- aes key。shiro默認的key是不安全的,能夠使用工程utils包的GenerateAESKey生成一個自定義的key-->
            <property name="cipherKey" value="#{T(org.apache.shiro.codec.Base64).decode('XgGkgqGqYrix9lI6vxcrRw==')}"/>
        </bean>
        <bean id="sessionManager"
              class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager">
            <property name="sessionDAO" ref="sessionDAO"/>
            <property name="sessionIdCookieEnabled" value="true"/>
            <property name="sessionIdCookie" ref="sessionIdCookie"/>
            <property name="deleteInvalidSessions" value="true" />
            <property name="sessionValidationSchedulerEnabled" value="true" />
        </bean>
        <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
            <property name="realm" ref="myRealm"/>
            <!-- shiro使用redis緩存 -->
            <property name="cacheManager" ref="redisCacheManager" />
            <property name="sessionManager" ref="sessionManager" />
            <!-- 客戶端勾選記住 -->
            <property name="rememberMeManager" ref="rememberMeManager"/>
        </bean>
        <bean id="redisCacheManager" class="com.zhm.ssr.shiro.RedisCacheManager" >
            <property name="redisManager" ref="redisManager" />
        </bean>
        <bean id="redisManager" class="com.zhm.ssr.shiro.RedisManager">
            <property name="expire" value="${redis.expireTime}" />
            <property name="host" value="${redis.host}" />
            <property name="password" value="${redis.pass}" />
            <property name="port" value="${redis.port}" />
            <property name="timeout" value="${redis.maxWait}" />
        </bean>
        <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
            <property name="securityManager" ref="securityManager"/>
            <property name="loginUrl" value="/login.html"/>
            <property name="unauthorizedUrl" value="/nolimit.html"/>
            <property name="filters">
                <map>
                    <entry key="mainFilter">
                        <bean class="com.zhm.ssr.filters.CustomAuthorizationFilter" />
                    </entry>
                </map>
            </property>
            <property name="filterChainDefinitions">
                <!-- 登陸頁面的全部請求,包括資源文件所有設定爲匿名
                     修改用戶信息功能須要驗證登陸,其餘都使用user過濾器。即rememberMe功能。
                -->
                <value>
                    /login**=anon
                    /user/doLogin**=anon
                    /lib/login.js=anon
                    /css/theme.css=anon
                    /favicon.ico=anon
                    /lib/font-awesome/css/font-awesome.css=anon
                    /js/html5.js=anon
                    /user/edit/**=authc,perms[admin:manage]
                    /**=mainFilter,user
                </value>
            </property>
        </bean>
        <!-- 自定義shiro的sessionDao,把session寫入redis -->
        <bean id="sessionDAO" class="com.zhm.ssr.shiro.RedisSessionDao">
            <constructor-arg ref="redisTemplate" />
            <constructor-arg value="${redis.expireTime}" />
        </bean>
        <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>

        <!-- @shiro註解拋出異常以後跳轉的頁面。-->
        <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
            <property name="exceptionMappings">
                <props>
                    <prop key="org.apache.shiro.authz.UnauthorizedException">
                        redirect:/nolimit.html
                    </prop>
                    <prop key="org.apache.shiro.authz.UnauthenticatedException">
                        redirect:/login.html
                    </prop>
                </props>
            </property>
        </bean>
        <!--  ========shiro 配置結束 ======== -->

        <!--  spring-data-redis配置,主要用做redis緩存 begin -->
        <bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
              p:host-name="${redis.host}" p:port="${redis.port}" p:password="${redis.pass}" p:timeout="5000"/>
        <bean id="stringRedisSerializer" class="org.springframework.data.redis.serializer.StringRedisSerializer" />
        <bean id="jdkSerializationRedisSerializer" class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer" />
        <bean id="stringRedisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate"
              p:connection-factory-ref="connectionFactory">
            <property name="KeySerializer" ref="stringRedisSerializer" />
            <property name="ValueSerializer" ref="stringRedisSerializer" />
            <property name="hashKeySerializer" ref="stringRedisSerializer" />
            <property name="hashValueSerializer" ref="stringRedisSerializer" />
        </bean>
        <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate"
              p:connection-factory-ref="connectionFactory">
            <property name="KeySerializer" ref="stringRedisSerializer" />
            <property name="ValueSerializer" ref="jdkSerializationRedisSerializer" />
            <property name="hashKeySerializer" ref="stringRedisSerializer" />
            <property name="hashValueSerializer" ref="jdkSerializationRedisSerializer" />
            <property name="enableTransactionSupport" value="true" />
        </bean>
        <!--  spring-data-redis配置,主要用做redis緩存 end -->

        <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
            <property name="driverClassName" value="${jdbch2.driverClassName}" />
            <property name="url" value="${jdbch2.url}" />
            <property name="username" value="${jdbch2.username}" />
            <property name="password" value="${jdbch2.password}" />
            <property name="validationQuery" value="select 1 " />
        </bean>
        <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
            <property name="dataSource"><ref bean="dataSource"/></property>
        </bean>
        <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
            <property name="dataSource" ref="dataSource"/>
        </bean>
        <tx:annotation-driven transaction-manager="txManager"/>
</beans>
相關文章
相關標籤/搜索