springboot+redis管理shiro session实现session集群

springboot集成shiro后,shiro将封装java web session,实现了自己的session管理机制,要使得session达到集群下的共享功能,就需要将session进行统一管理,这里我们可以使用redis缓存数据库实现session的存储

实现思路:
1、RedisSessionDao继承EnterpriseCacheSessionDAO,完成session的底层CRUD数据库操作,说白了,就是在redis缓存中对session的增删改查操作
2、ShiroConfig中注入redisSessionDao

具体实现:

1. RedisSessionDao

package com.sj.vip.shiro;

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

import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import com.sj.vip.utils.LoggerUtil;

/**
 * redis实现session共享
 * @author Administrator
 *
 */
@Component
public class RedisSessionDao extends EnterpriseCacheSessionDAO{

    //session在redis中的过期时间:30分钟 30*60s
    private static final int expireTime = 1800;
    
    //redis中session名称前缀
    private static String prefix = "sessionId:";
    
    @Autowired
    private RedisTemplate redisTemplate;
    
    // 创建session,保存到数据库
    @Override
    protected Serializable doCreate(Session session) {
        Serializable sessionId = super.doCreate(session);
        LoggerUtil.info(getClass(), "创建session:"+session.getId());
        redisTemplate.opsForValue().set(prefix + sessionId.toString(), session);
        return sessionId;
    }
    
    // 获取session
    @Override
    protected Session doReadSession(Serializable sessionId) {
        LoggerUtil.info(getClass(), "读取session:"+sessionId);
        // 先从缓存中获取session,如果没有再去数据库中获取
        Session session = super.doReadSession(sessionId);
        if(session == null){
            session = (Session) redisTemplate.opsForValue().get(prefix + sessionId.toString());
        }
        return session;
    }

    // 更新session的最后一次访问时间
    @Override
    protected void doUpdate(Session session) {
        super.doUpdate(session);
        LoggerUtil.info(getClass(), "更新session:"+session.getId());
        String key = prefix + session.getId().toString();
        if (!redisTemplate.hasKey(key)) {
            redisTemplate.opsForValue().set(key, session);
        }
        redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
    }

    //删除session
    @Override
    protected void doDelete(Session session) {
        LoggerUtil.info(getClass(), "删除session:"+session.getId());
        super.doDelete(session);
        redisTemplate.delete(prefix + session.getId().toString());
    }
    
    //获取当前活动的session
    @Override
    public Collection getActiveSessions() {
        return super.getActiveSessions();
    }
    
}

2. ShiroConfig

package com.sj.vip.shiro;

import java.util.LinkedHashMap;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.session.mgt.SessionManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ShiroConfig {
    
    @Autowired
    RedisSessionDao sessionDao;
    
    @Bean
    public SessionManager sessionManager() {
        DefaultWebSessionManager sessionManager = new DefaultWebSessionManager();
        sessionManager.setSessionDAO(sessionDao);
//        sessionManager.setGlobalSessionTimeout(1800);
//        SecurityUtils.getSubject().getSession().setTimeout(-1000l);
        return sessionManager;
    }
    
    //配置核心安全事务管理器
    @Bean
    public DefaultWebSecurityManager securityManager() {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(authRealm());
        securityManager.setSessionManager(sessionManager());
        return securityManager;
    }
    
    @Bean
    public ShiroFilterFactoryBean shiroFilter(@Qualifier("securityManager") SecurityManager manager){
        MyShiroFilterFactoryBean bean = new MyShiroFilterFactoryBean();
        bean.setSecurityManager(manager);
        //LoginUrl是用户首次进入时的登陆页面
        //SuccessUrl是登陆成功后自动跳转的页面
        //authc是需要用户登陆才能访问的页面
        //anon是不需要登陆就能直接访问的页面
        bean.setLoginUrl("/login");
        bean.setUnauthorizedUrl("/403");
        //配置访问权限 拦截器
        LinkedHashMap filterChainDefinitionMap=new LinkedHashMap();
        filterChainDefinitionMap.put("/static/**", "anon");//表示可以匿名访问
        filterChainDefinitionMap.put("/", "anon"); 
        filterChainDefinitionMap.put("/index", "anon"); 
        filterChainDefinitionMap.put("/login", "anon"); 
        filterChainDefinitionMap.put("/logout", "anon");
        filterChainDefinitionMap.put("/register","anon");
        filterChainDefinitionMap.put("/checkUsernameExists","anon");
        filterChainDefinitionMap.put("/403","anon");
        filterChainDefinitionMap.put("/qqLogin", "anon");
        filterChainDefinitionMap.put("/qqCallback", "anon");
        filterChainDefinitionMap.put("/wxLogin", "anon"); 
        filterChainDefinitionMap.put("/wxCallback", "anon");
        filterChainDefinitionMap.put("/*", "authc");//表示需要认证才可以访问
        bean.setFilterChainDefinitionMap(filterChainDefinitionMap);
        return bean;
    }
    
    //身份认证
    @Bean
    public AuthRealm authRealm() {
        AuthRealm authRealm = new AuthRealm();
        return authRealm;
    }
    
//    //配置自定义的权限登录器
//    @Bean(name="authRealm")
//    public AuthRealm authRealm(@Qualifier("credentialsMatcher") CredentialsMatcher matcher) {
//        AuthRealm authRealm=new AuthRealm();
//        authRealm.setCredentialsMatcher(matcher);
//        return authRealm;
//    }
    
}

你可能感兴趣的:(springboot+redis管理shiro session实现session集群)