分布式Shiro,SpringBoot项目Shiro整合Redis

分布式Shiro,SpringBoot项目Shiro整合Redis

====================重要 Begin====================

你的SpringBoot项目已经使用了Shiro,并且可以正常使用。本篇文章的主要目的是将Shiro保存在服务器内存中的session信息改为使用Redis保存session信息
====================重要 End====================

正文开始

0、前情概要

由于shiro不支持分布式场景下使用(可能是支持,但没找到),但是现在项目都是分布式的项目,一个服务要部署多个实例,明显shiro已经无法满足现有的情况。为了使shiro可以在分布式项目中使用,博主查阅了很多资料,其中一个包括引入shiro-redis依赖来实现(并未实操),但是看这个依赖最新的版本还是在2020年,果断放弃(应该有很多漏洞,我司对漏洞的把控极为严格!!!),所以就想着是否可以根据目前掌握的技术和网上的实践来手动实现一下shiro整合redis。以下就是博主的实现过程(码多话少,有事滴滴~)

1、引入依赖

xml 复制代码
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-pool2</artifactId>
</dependency>

2、创建Redis配置类

java 复制代码
/**
 * Redis配置类
 */
@EnableCaching
@Configuration
public class RedisConfiguration {

    @Autowired
    RedisCacheProperties redisCacheProperties;

    @Bean()
    public RedisTemplate<String, Object> redisShiroTemplate(@Autowired RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(factory);
        template.setKeySerializer(new StringRedisSerializer());
        template.setHashKeySerializer(new StringRedisSerializer());
        // shiro序列化存储session存在问题(https://www.cnblogs.com/ReturnOfTheKing/p/18224205)
        /*template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());*/
        return template;
    }

    @Bean(name = {"cacheKeyGenerator"})
    public KeyGenerator cacheKeyGenerator() {
        return (Object o, Method method, Object... objects) -> {
            StringBuilder sb = new StringBuilder();
            sb.append(o.getClass().getName());
            sb.append(method.getName());
            for (Object obj : objects) {
                sb.append(obj.toString());
            }
            return sb.toString();
        };
    }

    @Bean(name = "cacheManager")
    public RedisCacheManager cacheManager(@Autowired RedisConnectionFactory redisConnectionFactory) {

        RedisCacheConfiguration defaultConfig = RedisCacheConfiguration.defaultCacheConfig()
                .entryTtl(Duration.ofDays(7))
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()))
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()))
                .disableCachingNullValues();
        RedisCacheManager.RedisCacheManagerBuilder builder =
                RedisCacheManager.RedisCacheManagerBuilder.fromConnectionFactory(redisConnectionFactory);

        Set<String> cacheNames = new HashSet<>();
        ConcurrentHashMap<String, RedisCacheConfiguration> cacheConfig = new ConcurrentHashMap<>();

        for (Map.Entry<String, Duration> entry : redisCacheProperties.getCacheDuration().entrySet()) {
            cacheNames.add(entry.getKey());
            cacheConfig.put(entry.getKey(), defaultConfig.entryTtl(entry.getValue()));
        }

        RedisCacheManager cacheManager = builder
                .transactionAware()
                .cacheDefaults(defaultConfig)
                .initialCacheNames(cacheNames)
                .withInitialCacheConfigurations(cacheConfig)
                .build();

        return cacheManager;
    }
}
java 复制代码
/**
 * RedisCache参数
 */
@Component
@Getter
public class RedisCacheProperties {

    private final Map<String, Duration> cacheDuration = new HashMap<>();
}

3、继承AbstractSessionDAO,创建自定义RedisSessionDao 类

java 复制代码
/**
 * 自定义RedisSessionDAO
 */
@Component
public class RedisSessionDao extends AbstractSessionDAO {

    @Value("${session.redis.expireTime}")
    private long expireTime;

    @Autowired
    private RedisTemplate<String, Object> redisShiroTemplate;

    private String getKey(String originalKey) {
        return "shiro_redis_session_key_:" + originalKey;
    }

    @Override
    protected Serializable doCreate(Session session) {
        Serializable sessionId = this.generateSessionId(session);
        this.assignSessionId(session, sessionId);
        redisShiroTemplate.opsForValue().set(getKey(session.getId().toString()), session, expireTime, TimeUnit.SECONDS);
        return sessionId;
    }

    @Override
    protected Session doReadSession(Serializable sessionId) {
        return sessionId == null ? null : (Session) redisShiroTemplate.opsForValue().get(getKey(sessionId.toString()));
    }

    @Override
    public void update(Session session) throws UnknownSessionException {
        if (session != null && session.getId() != null) {
            session.setTimeout(expireTime * 1000);
            redisShiroTemplate.opsForValue().set(getKey(session.getId().toString()), session, expireTime, TimeUnit.SECONDS);
        }
    }

    @Override
    public void delete(Session session) {
        if (session != null && session.getId() != null) {
            redisShiroTemplate.opsForValue().getOperations().delete(getKey(session.getId().toString()));
        }
    }

    @Override
    public Collection<Session> getActiveSessions() {
        return Collections.emptySet();
    }
}

4、在ShiroConfiguration配置类中使用自定义SessionDAO

java 复制代码
@Bean
public SessionManager shiroSessionManager() {
    DefaultWebSessionManager sessionManager = new DefaultWebSessionManager();
    //session过期时间
    sessionManager.setGlobalSessionTimeout(expireTime * 1000);
    sessionManager.setSessionDAO(redisSessionDao);
    return sessionManager;
}

问题

往redis中放的数据记得实现 序列化接口,不然会报错!

参考

  1. 分布式shiro,session共享
  2. Shiro权限管理框架(二):Shiro结合Redis实现分布式环境下的Session共享
  3. shiro org.apache.shiro.session.mgt.SimpleSession对象 反序列化失败
相关推荐
爱上语文38 分钟前
Springboot的三层架构
java·开发语言·spring boot·后端·spring
荆州克莱40 分钟前
springcloud整合nacos、sentinal、springcloud-gateway,springboot security、oauth2总结
spring boot·spring·spring cloud·css3·技术
小宋102141 分钟前
玩转RabbitMQ声明队列交换机、消息转换器
服务器·分布式·rabbitmq
serve the people41 分钟前
springboot 单独新建一个文件实时写数据,当文件大于100M时按照日期时间做文件名进行归档
java·spring boot·后端
小安运维日记2 小时前
Linux云计算 |【第四阶段】NOSQL-DAY1
linux·运维·redis·sql·云计算·nosql
罗政6 小时前
[附源码]超简洁个人博客网站搭建+SpringBoot+Vue前后端分离
vue.js·spring boot·后端
懒洋洋的华3696 小时前
消息队列-Kafka(概念篇)
分布式·中间件·kafka
码农郁郁久居人下7 小时前
Redis的配置与优化
数据库·redis·缓存
March€7 小时前
分布式事务的基本实现
分布式
Hsu_kk8 小时前
Redis 主从复制配置教程
数据库·redis·缓存