Shrio+Redis实现tomcat集群session共享

本文涉及的产品
云数据库 Redis 版,社区版 2GB
推荐场景:
搭建游戏排行榜
简介: 一、背景   当我们使用了nginx做项目集群以后,就会出现一个很严重的问题亟待解决,那就是: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缓存同步的问题,如果你有好的办法,欢迎讨论交流学习!

相关实践学习
基于Redis实现在线游戏积分排行榜
本场景将介绍如何基于Redis数据库实现在线游戏中的游戏玩家积分排行榜功能。
云数据库 Redis 版使用教程
云数据库Redis版是兼容Redis协议标准的、提供持久化的内存数据库服务,基于高可靠双机热备架构及可无缝扩展的集群架构,满足高读写性能场景及容量需弹性变配的业务需求。 产品详情:https://www.aliyun.com/product/kvstore &nbsp; &nbsp; ------------------------------------------------------------------------- 阿里云数据库体验:数据库上云实战 开发者云会免费提供一台带自建MySQL的源数据库&nbsp;ECS 实例和一台目标数据库&nbsp;RDS实例。跟着指引,您可以一步步实现将ECS自建数据库迁移到目标数据库RDS。 点击下方链接,领取免费ECS&amp;RDS资源,30分钟完成数据库上云实战!https://developer.aliyun.com/adc/scenario/51eefbd1894e42f6bb9acacadd3f9121?spm=a2c6h.13788135.J_3257954370.9.4ba85f24utseFl
相关文章
|
3天前
|
NoSQL Redis
透视Redis集群:心跳检测如何维护高可用性
Redis心跳检测保障集群可靠性,通过PING命令检测主从连接状态,预防数据丢失。当连接异常时,自动触发主从切换。此外,心跳检测辅助实现`min-slaves-to-write`和`min-slaves-max-lag`策略,避免不安全写操作。还有重传机制,确保命令无丢失,维持数据一致性。合理配置心跳检测,能有效防止数据问题,提升Redis集群的高可用性。关注“软件求生”获取更多Redis知识!
40 10
透视Redis集群:心跳检测如何维护高可用性
|
6天前
|
监控 NoSQL 算法
Redis集群模式:高可用性与性能的完美结合!
小米探讨Redis集群模式,通过一致性哈希分散负载,主从节点确保高可用性。节点间健康检测、主备切换、数据复制与同步、分区策略和Majority选举机制保证服务可靠性。适合高可用性及性能需求场景,哨兵模式则适用于简单需求。一起学习技术的乐趣!关注小米微信公众号“软件求生”获取更多内容。
35 11
Redis集群模式:高可用性与性能的完美结合!
|
7天前
|
监控 NoSQL Redis
|
12天前
|
NoSQL Redis Docker
使用Docker搭建Redis主从集群
使用Docker搭建Redis主从集群
31 1
|
12天前
|
存储 NoSQL 算法
Redis 搭建分片集群
Redis 搭建分片集群
24 2
|
12天前
|
监控 NoSQL 算法
Redis 搭建哨兵集群
Redis 搭建哨兵集群
19 1
|
12天前
|
NoSQL 网络安全 Redis
Redis 搭建主从集群
Redis 搭建主从集群
18 0
|
运维 Oracle 关系型数据库
Tomcat集群session复制与Oracle的坑。。
问题描述 公司某个系统使用了tomcat自带的集群session复制功能,然后后报了一个oracle驱动包里面的连接不能被序列化的异常。
154 0
|
人工智能 Java 大数据
Tomcat集群session复制与Oracle的坑。。
​ image 问题描述 公司某个系统使用了tomcat自带的集群session复制功能,然后后报了一个oracle驱动包里面的连接不能被序列化的异常。
1651 0
|
12天前
|
XML Java 应用服务中间件
Tomcat_servlet部署、编译、配置、打包
Tomcat_servlet部署、编译、配置、打包
16 0