Spring+Shiro搭建基于Redis的分布式权限系统(有实例)
摘要: 简单介绍使用Spring+Shiro搭建基于Redis的分布式权限系统。
这篇主要介绍Shiro如何与redis结合搭建分布式权限系统,至于如何使用和配置Shiro就不多说了。完整实例下载地址:https://git.oschina.net/zhmlvft/spring_shiro_redis
要实现分布式,主要需要解决2个大问题。
第一个解决shiro session共享的问题。这个可以通过自定义sessionDao实现。继承 CachingSessionDao。
public class RedisSessionDao extends CachingSessionDAO {
private final static Logger log = LoggerFactory.getLogger(RedisSessionDao.class); private RedisTemplate<String, Object> redisTemplate;
private int defaultExpireTime = ; 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源码来实现。
附上spring中的完整配置如下:
<?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="" rejection-policy="CALLER_RUNS"/> <!-- redis缓存 -->
<bean id="cacheManager" class="org.springframework.data.redis.cache.RedisCacheManager" c:template-ref="redisTemplate">
<property name="defaultExpiration" value=""></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></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=""/><!-- 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>
Spring+Shiro搭建基于Redis的分布式权限系统(有实例)的更多相关文章
- 基于SkyWalking的分布式跟踪系统 - 异常告警
通过前面2篇文章我们搭建了SW的基础环境,监控了微服务,能了解所有服务的运行情况.但是当出现服务响应慢,接口耗时严重时我们需要立即定位到问题,这就需要我们今天的主角--监控告警,同时此篇也是SW系列的 ...
- 基于 Redis 的分布式锁
前言 分布式锁在分布式应用中应用广泛,想要搞懂一个新事物首先得了解它的由来,这样才能更加的理解甚至可以举一反三. 首先谈到分布式锁自然也就联想到分布式应用. 在我们将应用拆分为分布式应用之前的单机系统 ...
- 基于redis的分布式锁的分析与实践
前言:在分布式环境中,我们经常使用锁来进行并发控制,锁可分为乐观锁和悲观锁,基于数据库版本戳的实现是乐观锁,基于redis或zookeeper的实现可认为是悲观锁了.乐观锁和悲观锁最根本的区别在于 ...
- asp.net core mvc基于Redis实现分布式锁,C# WebApi接口防止高并发重复请求,分布式锁的接口幂等性实现
使用背景:在使用app或者pc网页时,可能由于网络原因,api接口可能被前端调用一个接口重复2次的情况,但是请求内容是一样的.这样在同一个短暂的时间内,就会有两个相同请求,而程序只希望处理第一个请求, ...
- 【redis】基于redis实现分布式并发锁
基于redis实现分布式并发锁(注解实现) 说明 前提, 应用服务是分布式或多服务, 而这些"多"有共同的"redis"; (2017-12-04) 笑哭, 写 ...
- 基于redis 实现分布式锁的方案
在电商项目中,经常有秒杀这样的活动促销,在并发访问下,很容易出现上述问题.如果在库存操作上,加锁就可以避免库存卖超的问题.分布式锁使分布式系统之间同步访问共享资源的一种方式 基于redis实现分布式锁 ...
- 基于redis的分布式锁
<?php /** * 基于redis的分布式锁 * * 参考开源代码: * http://nleach.com/post/31299575840/redis-mutex-in-php * * ...
- 基于Redis的分布式锁真的安全吗?
说明: 我前段时间写了一篇用consul实现分布式锁,感觉理解的也不是很好,直到我看到了这2篇写分布式锁的讨论,真的是很佩服作者严谨的态度, 把这种分布式锁研究的这么透彻,作者这种技术态度真的值得我好 ...
- 基于redis的分布式锁(转)
基于redis的分布式锁 1 介绍 这篇博文讲介绍如何一步步构建一个基于Redis的分布式锁.会从最原始的版本开始,然后根据问题进行调整,最后完成一个较为合理的分布式锁. 本篇文章会将分布式锁的实现分 ...
随机推荐
- Linux安装apache服务
1.通过yum包下载安装httpd yum -y install httpd*(等待安装) 到下面就安装完毕 2.启动apache服务 service httpd restart 3.现在就可以查看a ...
- BZOJ1226 SDOI2009学校食堂
这题状压DP太神了. g[i][j][k]表示前i-1个人都已打到饭,自己和后七个人打饭的情况是j,当前最后一个打饭的与i的关系是k 如果j&1==1说明当前这个人也打了饭,那么可以转移到g[ ...
- 【点分治】【路径小于等于k的条数】【路径恰好等于k是否存在】
POJ1741:Tree Time Limit: 1000MS Memory Limit: 30000K Total Submissions: 29574 Accepted: 9915 Des ...
- hdu 5211 Mutiple 数学
Mutiple Time Limit: 1 Sec Memory Limit: 256 MB 题目连接 http://acm.hdu.edu.cn/showproblem.php?pid=5211 ...
- MySQL 之 Index Condition Pushdown(ICP)
简介 Index Condition Pushdown (ICP)是MySQL 5.6 版本中的新特性,是一种在存储引擎层使用索引过滤数据的一种优化方式. 当关闭ICP时,index 仅仅是data ...
- PHP简单利用 token 防止表单重复提交
<?php /* * 隐藏一个可变的token,每次提交都需要和服务器校对 */ session_start(); function set_token() { $_SESSION['token ...
- iOS开发经验总结——基础工程
iOS开发经验总结--依赖库 这篇博客,我想说一下开发中经常遇到的一个问题,虚拟个场景描述一下的话,应该是这样的. 项目经理:今天我们正式开始一个新项目,iOSer你负责把苹果端的APP完成,有没有问 ...
- 使用ScrapySharp快速从网页中采集数据
ScrapySharp是一个帮助我们快速实现网页数据采集的库,它主要提供了如下两个功能 从Url获取Html数据 提供CSS选择器的方式解析Html节点 安装: ScrapySharp可以直接从Nug ...
- SQL SERVER 函数与SQL语法
http://www.cnblogs.com/hoojo/archive/2011/07/16/2108129.html
- myeclipse 8.5破解方法
转自: http://blog.sina.com.cn/s/blog_70600f7201018pib.html , 记录下来存档 Step: 1.建立一个任意名称的Java Project 2.在 ...