springboot2.x中,shiro使用redis缓存
程序员文章站
2022-07-07 11:38:10
...
环境:srpingboot 2.1.1.RELEASE
依赖:
<!-- shiro+redis缓存插件 -->
<dependency>
<groupId>org.crazycake</groupId>
<artifactId>shiro-redis</artifactId>
<version>2.4.2.1-RELEASE</version>
</dependency>
要让shiro使用redis缓存,有两种方法。第一种需要重新实现shiro的cache、cacheManager、SessionDAO,这三个接口都是apache shiro自己的,和spring没关系。这种方法比较麻烦,我们采用第二种,使用shiro-redis开源插件。首先要在pom里依赖它,然后改写ShiroConfig.java里的几个方法。
/**
* cacheManager 缓存 redis实现
* 使用的是shiro-redis开源插件
*
* @return
*/
@Bean(name = "redisCacheManager")
public RedisCacheManager cacheManager() {
RedisCacheManager redisCacheManager = new RedisCacheManager();
redisCacheManager.setRedisManager(redisManager());
return redisCacheManager;
}
/**
* 配置shiro redisManager
* 使用的是shiro-redis开源插件
*
* @return
*/
@Bean
public RedisManager redisManager() {
RedisManager redisManager = new RedisManager();
redisManager.setHost("localhost");
redisManager.setPort(6379);
redisManager.setExpire(1800);// 配置缓存过期时间
redisManager.setTimeout(0);
// redisManager.setPassword(password);
return redisManager;
}
/**
* Session Manager
* 使用的是shiro-redis开源插件
*/
@Bean
public DefaultWebSessionManager sessionManager() {
DefaultWebSessionManager sessionManager = new DefaultWebSessionManager();
sessionManager.setSessionDAO(redisSessionDAO());
return sessionManager;
}
/**
* RedisSessionDAO shiro sessionDao层的实现 通过redis
* 使用的是shiro-redis开源插件
*/
@Bean
public RedisSessionDAO redisSessionDAO() {
RedisSessionDAO redisSessionDAO = new RedisSessionDAO();
redisSessionDAO.setRedisManager(redisManager());
return redisSessionDAO;
}
/**
* 会话验证调度器
*
* @return
*/
@Bean
public ExecutorServiceSessionValidationScheduler sessionValidationScheduler(DefaultWebSessionManager sessionManager) {
ExecutorServiceSessionValidationScheduler sessionValidationScheduler = new ExecutorServiceSessionValidationScheduler();
sessionValidationScheduler.setInterval(3600000L);
sessionValidationScheduler.setSessionManager(sessionManager);
return sessionValidationScheduler;
}
/**
* 凭证匹配器
*
* @return
*/
@Bean
public RetryLimitHashedCredentialsMatcher credentialsMatcher(RedisCacheManager redisCacheManager) {
RetryLimitHashedCredentialsMatcher credentialsMatcher = new RetryLimitHashedCredentialsMatcher(redisCacheManager);
credentialsMatcher.setHashAlgorithmName("md5");
credentialsMatcher.setHashIterations(2);
credentialsMatcher.setStoredCredentialsHexEncoded(true);
return credentialsMatcher;
}
上面的代码除了会话验证调度器都需要改动。这样就完成了shiro和redis的整合,shiro的会话信息将会存储在redis里面。redis的连接信息需要单独在redisManager()里面配置。