apache shiro 如何升级_实战,通过复写shiro的SessionDAO来实现将session保存到redis集群中...

d187ddd3bd9550352ff97899f2d19dd3.png

作者:zifangsky

https://www.zifangsky.cn/889.html

如题所示,在分布式系统架构中需要解决的一个很重要的问题就是——如何保证各个应用节点之间的Session共享。现在通用的做法就是使用redis、memcached等组件独立存储所有应用节点的Session,以达到各个应用节点之间的Session共享的目的

在Java Web项目中实现session共享的一个很好的解决方案是:Spring Session+Spring Data Redis。关于这方面的内容可以参考我之前写的这篇文章:https://www.zifangsky.cn/862.html

但是,如果在项目中使用到了shiro框架,并且不想使用Spring Session的话,那么我们可以通过复写shiro的SessionDAO同样达到将shiro管理的session保存到redis集群的目的,以此解决分布式系统架构中的session共享问题

下面,我将详细说明具体该如何来实现:

(1)配置Spring Data Redis环境:

关于Spring Data Redis环境的配置可以参考这篇文章:

https://www.zifangsky.cn/861.html

在这里,我测试使用的是redis集群模式,当然使用redis单节点也可以

(2)复写shiro的SessionDAO:

import java.io.Serializable;
import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;

import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;

@Repository("customShiroSessionDao")
public class CustomShiroSessionDao extends EnterpriseCacheSessionDAO {

    @Resource(name="redisTemplate")
    private RedisTemplate redisTemplate;/**
     * 创建session,保存到redis集群中
     */@Overrideprotected Serializable doCreate(Session session) {
        Serializable sessionId = super.doCreate(session);
        System.out.println("sessionId: " + sessionId);
        BoundValueOperations sessionValueOperations = redisTemplate.boundValueOps("shiro_session_" + sessionId.toString());
        sessionValueOperations.set(session);
        sessionValueOperations.expire(30, TimeUnit.MINUTES);return sessionId;
    }/**
     * 获取session
     * @param sessionId
     * @return
     */@Overrideprotected Session doReadSession(Serializable sessionId) {
        Session session = super.doReadSession(sessionId);if(session == null){
            BoundValueOperations sessionValueOperations = redisTemplate.boundValueOps("shiro_session_" + sessionId.toString());
            session = (Session) sessionValueOperations.get();
        }return session;
    }/**
     * 更新session
     * @param session
     */@Overrideprotected void doUpdate(Session session) {super.doUpdate(session);
        BoundValueOperations sessionValueOperations = redisTemplate.boundValueOps("shiro_session_" + session.getId().toString());
        sessionValueOperations.set(session);
        sessionValueOperations.expire(30, TimeUnit.MINUTES);
    }/**
     * 删除失效session
     */@Overrideprotected void doDelete(Session session) {
        redisTemplate.delete("shiro_session_" + session.getId().toString());super.doDelete(session);
    }
}

具体含义可以参考注释,这里就不多做解释了

(3)在shiro的配置文件中添加sessionManager:

    
    <bean id="sessionManager"  class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager"> 
        
        <property name="sessionValidationSchedulerEnabled" value="true" />  
         
        <property name="globalSessionTimeout" value="1800000" />
        <property name="sessionDAO" ref="customShiroSessionDao" />  
    bean>

然后在securityManager中使用该sessionManager:

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

注:完整的shiro的配置文件如下:

<?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:jee="http://www.springframework.org/schema/jee"xsi:schemaLocation="http://www.springframework.org/schema/beans 
            http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
            http://www.springframework.org/schema/jee 
            http://www.springframework.org/schema/jee/spring-jee-4.0.xsd
            http://www.springframework.org/schema/aop 
            http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
            http://www.springframework.org/schema/context 
            http://www.springframework.org/schema/context/spring-context-4.0.xsd
            http://www.springframework.org/schema/tx 
            http://www.springframework.org/schema/tx/spring-tx-4.0.xsd"xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"xmlns:aop="http://www.springframework.org/schema/aop">
    <description>Shiro 配置description>

    <context:component-scan base-package="cn.zifangsky.manager.impl" />
    <context:component-scan base-package="cn.zifangsky.shiro" />

    <bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
        <property name="cacheManager" ref="cacheManagerFactory" />
        <property name="cacheManagerConfigFile" value="classpath:ehcache.xml" />
    bean>

    
    <bean id="sessionManager"  class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager"> 
        
        <property name="sessionValidationSchedulerEnabled" value="true" />  
         
        <property name="globalSessionTimeout" value="1800000" />
        <property name="sessionDAO" ref="customShiroSessionDao" />  
    bean>

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

    
    <bean id="customRealm" class="cn.zifangsky.shiro.CustomRealm" />

    <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
        <property name="securityManager" ref="securityManager" />
        <property name="loginUrl" value="/user/user/login.html" />
        
        <property name="unauthorizedUrl" value="/error/403.jsp" />
        
        <property name="filterChainDefinitions">
            <value>
                /error/* = anon
                /scripts/* = anon
                /user/user/check.html = anon
                /user/user/verify.html = anon
                /user/user/checkVerifyCode.html = anon
                /user/user/logout.html = logout
                /**/*.htm* = authc
        /**/*.json* = authc
            value>
        property>
    bean>

    
    <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>

beans>

(4)测试:

i)本地简单测试:

将同一项目部署到本地两个不同端口的Tomcat中,然后在其中一个Tomcat登录,接着直接在另一个Tomcat上访问登录后的URL,观察是否可以直接访问还是跳转到登录页面

ii)完整分布式环境测试:

首先将测试项目部署到两个服务器上的Tomcat中,我这里的访问路径分别是:

192.168.1.30:9080
192.168.1.31:9080

接着配置nginx访问(PS:nginx所在IP是:192.168.1.31):

server {
    server_name  localhost;
    listen 7888;

    location /WebSocketDemo
        {       
              proxy_redirect off;
              proxy_set_header        Host $host:7888;
              proxy_set_header        X-Real-IP $remote_addr;
              proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
              proxy_pass http://demo/WebSocketDemo;
              proxy_set_header   Cookie $http_cookie;
        }

    #access_log  on;
    limit_conn perip 1000;  #同一ip并发数为50,超过会返回503
    access_log logs/access_test.log zifangsky_log;
 }

对应的upstream是:

upstream demo {
  server 192.168.1.30:9080;
  server 192.168.1.31:9080;
}

从上面可以看出,这里设置的nginx的负载均衡策略是默认策略——轮询

最后在浏览器中访问:http://192.168.1.31:7888/WebSocketDemo/user/user/login.html

登录之后,不断刷新页面并观察nginx的日志:

308b8406ae56fa038a5c13122993cccd.png

可以发现,经过nginx的反向代理之后,虽然每次访问的实际服务地址都不一样,但是我们的登录状态并没有丢失——并没有跳转到登录页面。这就证明了这个测试小集群的session的确实现了共享,也就是说session保存到了redis集群中,并不受具体的业务服务器的更改而发生改变

当然,我们也可以登录到redis集群,查询一下该sessionId对应的session值:

6ae6621588349d758ddb6a071526c429.png

参考:

http://www.cnblogs.com/sunshine-2015/p/5686750.html

Java面试题专栏

【61期】MySQL行锁和表锁的含义及区别(MySQL面试第四弹)【62期】解释一下MySQL中内连接,外连接等的区别(MySQL面试第五弹)【63期】谈谈MySQL 索引,B+树原理,以及建索引的几大原则(MySQL面试第六弹)【64期】MySQL 服务占用cpu 100%,如何排查问题? (MySQL面试第七弹)【65期】Spring的IOC是啥?有什么好处?【66期】Java容器面试题:谈谈你对 HashMap 的理解【67期】谈谈ConcurrentHashMap是如何保证线程安全的?【68期】面试官:对并发熟悉吗?说说Synchronized及实现原理【69期】面试官:对并发熟悉吗?谈谈线程间的协作(wait/notify/sleep/yield/join)【70期】面试官:对并发熟悉吗?谈谈对volatile的使用及其原理

47122aa1e660a08acc434effd4482bfb.png

欢迎长按下图关注公众号后端技术精选

27bf006090cabe046b97e30793eeb080.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值