Shiro+Redis实现tomcat集群session共享
一、背景
当我们使用了nginx做项目集群以后,就会出现一个很严重的问题亟待解决,那就是:tomcat集群之间如何实现session共享的问题,如果这个问题不解决,就会出现登陆过后再次请求资源依旧需要登陆的问题。这篇文章我们就解决这个问题。
二、实现步骤
说明:本篇是在spring+shiro集成的基础上进行改进的,如果不知道spring和shiro怎么集成,请移步:spring集成shiro做登陆认证
1.在pom.xml中添加shiro-redis和jedis的依赖
<dependency>
<groupId>org.crazycake</groupId>
<artifactId>shiro-redis</artifactId>
<version>2.4.2.1-RELEASE</version>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.7.2</version>
</dependency>
2.首先我们需要对redis进行集成,在resources下新建config.properties
#redis pool config
redis.pool.maxActive=200
redis.pool.maxIdle=100
redis.pool.maxWait=100
redis.pool.testOnBorrow=true #redis config
redis.host=192.168.85.129
redis.port=6379
redis.timeout=2000
redis.password=123456
redis.dbindex=8
redis.default.expire=1800000
3.在resources/spring文件夹下新建spring-redis.xml来集成redis操作客户端
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd"> <description>Redis configuration</description> <bean id="redisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="maxTotal" value="${redis.pool.maxActive}"/>
<property name="maxIdle" value="${redis.pool.maxIdle}"/>
<property name="maxWaitMillis" value="${redis.pool.maxWait}"/>
<property name="testOnBorrow" value="${redis.pool.testOnBorrow}"/>
</bean> <bean id="jedisPool" class="redis.clients.jedis.JedisPool" destroy-method="destroy">
<constructor-arg ref="redisPoolConfig"/>
<constructor-arg value="${redis.host}"/>
<constructor-arg type="int" value="${redis.port}"/>
<constructor-arg type="int" value="${redis.timeout}"/>
<constructor-arg type="java.lang.String" value="${redis.password}"/>
<constructor-arg type="int" value="${redis.dbindex}"/>
</bean> <bean id="redisClient" class="com.hafiz.www.redis.RedisClient">
<constructor-arg name="jedisPool" ref="jedisPool"/>
<property name="expire" value="${redis.default.expire}"/>
</bean>
</beans>
4.添加redisClient.java作为访问redis的客户端
package com.hafiz.www.redis; import org.crazycake.shiro.RedisManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool; import java.util.Set; /**
* Desc: Jedis 操作客户端
* Created by hafiz.zhang on 2017/7/21.
*/
public class RedisClient extends RedisManager{ private static final Logger LOGGER = LoggerFactory.getLogger(RedisClient.class); private static JedisPool jedisPool = null; public RedisClient(JedisPool jedisPool) {
this.jedisPool = jedisPool;
} public void init() {
super.init();
} @Override
public byte[] get(byte[] key) {
Jedis jedis = jedisPool.getResource();
byte[] value; try {
value = jedis.get(key);
} catch (Exception e) {
LOGGER.error("redis key:{} get value occur exception", new String(key));
throw new RuntimeException("redis operation error:", e);
} finally {
jedis.close();
} return value;
} @Override
public byte[] set(byte[] key, byte[] value) {
Jedis jedis = jedisPool.getResource(); try {
jedis.set(key, value);
Integer expire = getExpire();
if(expire != 0) {
jedis.expire(key, expire);
}
} catch (Exception e) {
LOGGER.error("redis key:{} set value:{} occur exception", new String(key), new String(value));
throw new RuntimeException("redis operation error:", e);
} finally {
jedis.close();
} return value;
} @Override
public byte[] set(byte[] key, byte[] value, int expire) {
Jedis jedis = jedisPool.getResource(); try {
jedis.set(key, value);
if(expire != 0) {
jedis.expire(key, expire);
}
} catch (Exception e) {
LOGGER.error("redis key:{} set value:{} in expire:{} occur exception", new String(key), new String(value), expire);
throw new RuntimeException("redis operation error:", e);
} finally {
jedis.close();
} return value;
} @Override
public void del(byte[] key) {
Jedis jedis = jedisPool.getResource(); try {
jedis.del(key);
} catch (Exception e) {
LOGGER.error("redis key:{} del value occur exception", new String(key));
throw new RuntimeException("redis operation error:", e);
} finally {
jedis.close();
}
} @Override
public void flushDB() {
Jedis jedis = jedisPool.getResource(); try {
jedis.flushDB();
} catch (Exception e) {
LOGGER.error("redis flushDB occur exception");
throw new RuntimeException("redis operation error:", e);
} finally {
jedis.close();
} } @Override
public Long dbSize() {
Long dbSize = Long.valueOf(0L);
Jedis jedis = jedisPool.getResource(); try {
dbSize = jedis.dbSize();
} catch (Exception e) {
LOGGER.error("redis get dbSize occur exception");
throw new RuntimeException("redis operation error:", e);
} finally {
jedis.close();
} return dbSize;
} @Override
public Set<byte[]> keys(String pattern) {
Set keys = null;
Jedis jedis = jedisPool.getResource(); try {
keys = jedis.keys(pattern.getBytes());
} catch (Exception e) {
LOGGER.error("redis get keys in pattern:{} occur exception", pattern);
throw new RuntimeException("redis operation error:", e);
} finally {
jedis.close();
} return keys;
}
}
5.接着,我们对spring-shiro.xml做如下修改(红色标记的部分)
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util.xsd"> <description>Shiro Configuration</description> <!--shiro-redis redisCacheManager-->
<bean id="redisCacheManager" class="org.crazycake.shiro.RedisCacheManager">
<property name="keyPrefix" value="shiro_redis_session:"/>
<property name="redisManager" ref="redisClient"/>
</bean> <!--custom myself realm-->
<bean id="customRealm" class="com.hafiz.www.shiro.CustomRealm">
<property name="cacheManager" ref="redisCacheManager"/>
</bean> <!--redisSessionDAO-->
<bean id="redisSessionDAO" class="org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO"></bean> <!--simpleCookie,不定义在集群环境下会出现There is no session with id ....-->
<bean id="simpleCookie" class="org.apache.shiro.web.servlet.SimpleCookie">
<constructor-arg name="name" value="custom.session"/>
<property name="path" value="/"/>
</bean> <!--sessionManager-->
<bean id="sessionManager" class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager">
<property name="sessionDAO" ref="redisSessionDAO"/>
<property name="sessionIdCookie" ref="simpleCookie"/>
</bean> <!--Shiro`s main business-tier object for web-enable applications-->
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<property name="realm" ref="customRealm"/>
<property name="cacheManager" ref="redisCacheManager"/>
<property name="sessionManager" ref="sessionManager"/>
</bean> <!--shiro filter-->
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<property name="securityManager" ref="securityManager"/>
<property name="loginUrl" value="/login.html"/>
<property name="successUrl" value="/index.html"/>
<property name="unauthorizedUrl" value="/unauthorized.html"/>
<property name="filters">
<util:map>
<entry key="auth">
<bean class="com.hafiz.www.filter.AuthorizeFilter"/>
</entry>
</util:map>
</property>
<property name="filterChainDefinitions">
<value>
/login.json = anon
/logout.json = anon
/js/** = anon
/ = authc
/** = auth
</value>
</property>
</bean>
</beans>
6.spring.xml做如下修改
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd"> <context:property-placeholder location="classpath:config.properties,classpath:jdbc.properties"/>
<import resource="spring-*.xml"/> </beans>
到此我们就完了shiro+redis实现session共享的问题,其实也很简单,其中的实现逻辑也很简单,就是shiro的拦截器会首先去redis里面获取session,作为当本次请求的session.
其他代码以及简单测试代码不再贴出,给出github地址:https://github.com/hafizzhang/shiro-session-cluster.git
三、总结
通过本文,我们就完成了spring+shiro+redis实现集群session共享的问题,经过亲测可行。但有一点遗憾的地方,就是每次请求至少会有8次redis的读操作,一次写操作,这个问题还没有找到很好的解决办法,本地使用ehcahe也不太现实,因为涉及到本地缓存和redis缓存同步的问题,如果你有好的办法,欢迎讨论交流学习!
Shiro+Redis实现tomcat集群session共享的更多相关文章
- redis实现tomcat集群session共享
1.部署两个tomcat节点,使用nginx实现集群(见http://www.cnblogs.com/zhangzhi0556/articles/nginx.html): 2.redis安装(见h ...
- Nginx+Tomcat集群+session共享
Nginx+Tomcat集群+session共享 1)安装Nginx 2)配置多个Tomcat,在server.xml中修改端口(端口不出现冲突即可) 3)在nginx.conf文件中配置负载均衡池, ...
- JEECG & JEESite Tomcat集群 Session共享
多台tomcat服务的session共享 memcached与redis - JEECG开源社区 - CSDN博客https://blog.csdn.net/zhangdaiscott/article ...
- 160513、nginx+tomcat集群+session共享(linux)
第一步:linux中多个tomcat安装和jdk安装(略) 第二步:nginx安装,linux中安装nginx和windows上有点不同也容易出错,需要编译,这里做介绍 一.安装依赖 gcc open ...
- tomcat集群session共享
Tomcat集群配置其实很简单,在Tomcat自带的文档中有详细的说明( /docs/cluster-howto.html ),只不过是英语的,对我这样的人来说很难懂 . 下面根据说下怎么配置 ...
- 160512、nginx+多个tomcat集群+session共享(windows版)
第一步:下载nginx的windows版本,解压即可使用,点击nginx.exe启动nginx 或cmd命令 1.启动: D:\nginx+tomcat\nginx-1.9.3>start ng ...
- 基于Memcached的tomcat集群session共享所用的jar
多个tomcat各种序列化策略配置如下:一.java默认序列化tomcat配置conf/context.xml添加<Manager className="de.javakaffee.w ...
- 基于Memcached的tomcat集群session共享所用的jar及多个tomcat各种序列化策略配置
原文:http://www.cnblogs.com/interdrp/p/4096466.html 多个tomcat各种序列化策略配置如下:一.java默认序列化tomcat配置conf/contex ...
- 使用memcached实现tomcat集群session共享
环境centos6.7,下载安装必要的软件:yum -y install epel-release(tomcat7在此源上,tomcat7是现在主流版本) yum -y install tomcat ...
随机推荐
- 什么是 java.awt.headless
以下是网上的说法,我觉得简单地说就是有些功能需要硬件设备协助,比如显卡,但如果是服务器可能都没装显卡,这时就需要JDK调用自身的库文件去摸拟显卡的功能. 什么是 java.awt.headless? ...
- SharePoint 2010 安装错误:请重新启动计算机,然后运行安装程序以继续
一.环境:Windows Server 2008 R2 with sp1,SharePoint 2010 二.问题描述: 正常的安装SharePoint 2010 ,安装完必备组件,并提示所有必备组件 ...
- Kendo ui 入门知识点
1. Kendo的继承 varPerson= kendo.Class.extend({...}); var person = new person(); var Parent = kendo.Clas ...
- 讨论HTTP POST 提交数据的几种方式
转自:http://www.cnblogs.com/softidea/p/5745369.html HTTP/1.1 协议规定的 HTTP 请求方法有 OPTIONS.GET.HEAD.POST.PU ...
- FS 日志空间限定
一.说明: FS默认安装的log文件,仅仅的限制了每个文件的大小,但是没有限制文件的个数.这种情况下,在FS运行很长时间之后,会出现物理空间不够的情况,导致FS或者mysql 或者其他应用没有空间使用 ...
- vue-cli(vue脚手架)超详细教程
都说Vue2简单上手容易,的确,看了官方文档确实觉得上手很快,除了ES6语法和webpack的配置让你感到陌生,重要的是思路的变换,以前用jq随便拿全局变量和修改dom的锤子不能用了,vu ...
- Ex 2_34 线性3SAT..._第四次作业
- 单点登录SSO的原理及实现方式总结
核心思想 用户信息的集中存储(全局Cooike.集中式Session.Json Web Token.Redis缓存服务器.自定义SSO服务器) 认证(Filter中执行) 登出(不同站 ...
- Django 笔记(三)模版路径 ~ 静态引用
1.模版路径: 在 settings,py 里的 TEMPLATES = [] 内添加一句代码拼接路径 'DIRS': [os.path.join(BASE_DIR, 'templates')] 有两 ...
- dubbo常用网址
https://dubbo.gitbooks.io/dubbo-user-book/content/references/protocol/dubbo.html http://dubbo.apache ...