因为用户认证与授权需要从数据库中查询并验证信息,但是对于权限很少改变的情况,这样不断从数据库中查询角色验证权限,对整个系统的开销很大,对数据库压力也随之增大。因此可以将用户认证和授权信息都缓存起来,第一次缓存没有的时候会自动从数据库中获取,并添加到缓存中;如果缓存中已经有该登录用户的认证和权限信息就直接从缓存中拿

使用CacheManager

Cache的作用

  • 用来减轻数据库的访问压力,从而提升查询效率。

  • 流程

使用默认的EhCache实现缓存

1、引入Ehcache相关依赖

<!-- https://mvnrepository.com/artifact/org.apache.shiro/shiro-ehcache -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-ehcache</artifactId>
<version>1.4.0</version>
</dependency>

2、开启缓存

在ShiroConfig配置类中,找到注入的Realm方法,开启缓存

 @Bean
public Realm getRealm() {
CustomRelam customRelam = new CustomRelam();
// 创建校验匹配器
HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
// 散列1024次
hashedCredentialsMatcher.setHashIterations(1024);
// 加密算法是MD5
hashedCredentialsMatcher.setHashAlgorithmName("md5");
customRelam.setCredentialsMatcher(hashedCredentialsMatcher); // 开启全局缓存
customRelam.setCachingEnabled(true);
// 开启认证缓存
customRelam.setAuthenticationCachingEnabled(true);
// 设置认证缓存管理的名字
customRelam.setAuthenticationCacheName("authenticationCache");
// 开启授权缓存管理
customRelam.setAuthorizationCachingEnabled(true);
// 设置授权缓存管理的名字
customRelam.setAuthorizationCacheName("authorizationCache");
// 开启缓存
customRelam.setCacheManager(new EhCacheManager()); return customRelam;
}

开启缓存后第一次认证与授权需要查询数据库,以后再不修改用户权限或者密码的情况下都是从缓存中取出数据。

Shiro使用Redis做缓存

1、引入相关依赖

<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<version>2.3.2.RELEASE</version>
</dependency>

2、配置redis连接

spring.redis.database=0
spring.redis.port=6379
spring.redis.host=127.0.0.1
# 链接超时时间 单位 ms(毫秒)
spring.redis.timeout=3000
################ Redis 线程池设置 ##############
# 连接池最大连接数(使用负值表示没有限制) 默认 8
spring.redis.jedis.pool.max-active=8
# 连接池最大阻塞等待时间(使用负值表示没有限制) 默认 -1
spring.redis.jedis.pool.max-wait=-1
# 连接池中的最大空闲连接 默认 8
spring.redis.jedis.pool.max-idle=8
# 连接池中的最小空闲连接 默认 0
spring.redis.jedis.pool.min-idle=0

3、启动redis服务

Windows下进入redis目录,先启动redis-server.exe,然后启动redis-cli.exe

进入命令行

然后在cache包下创建RedisCacheManager实现CacheManager接口

public class RedisCacheManager implements CacheManager {
@Override
public <K, V> Cache<K, V> getCache(String cacheKey) throws CacheException {
return new RedisCache<>(cacheKey);
}
}

创建RedisCache实现Cache接口

public class RedisCache<K, V> implements Cache<K, V> {
private String cacheName; public RedisCache() {
} public RedisCache(String cacheName) {
this.cacheName = cacheName;
} private RedisTemplate getRedisTemplate() {
RedisTemplate redisTemplate = (RedisTemplate) ApplicationContextUtil.getBean("redisTemplate");
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
return redisTemplate;
} @Override
public V get(K k) throws CacheException { return (V) getRedisTemplate().opsForHash().get(this.cacheName,k.toString()); } @Override
public V put(K k, V v) throws CacheException { getRedisTemplate().opsForHash().put(this.cacheName,k.toString(), v);
return null;
} @Override
public V remove(K k) throws CacheException { return (V) getRedisTemplate().opsForHash().delete(this.cacheName,k.toString());
} @Override
public void clear() throws CacheException {
getRedisTemplate().opsForHash().delete(this.cacheName);
} @Override
public int size() {
return getRedisTemplate().opsForHash().size(this.cacheName).intValue();
} @Override
public Set<K> keys() {
return getRedisTemplate().opsForHash().keys(this.cacheName);
} @Override
public Collection<V> values() {
return getRedisTemplate().opsForHash().values(this.cacheName);
}
}

由于自定义realm中认证所需要的盐值内部并没有实现序列化接口,所以我们需要自己定一个MyByteSource继承SimpleByteSource并实现Serializable接口

import org.apache.shiro.util.SimpleByteSource;

import java.io.Serializable;

public class MyByteSource extends SimpleByteSource implements Serializable {
public MyByteSource(String string) {
super(string);
}
}

在自定义的Realm中需要在认证的方法中,改写salt的处理。

  • 注意实体类(角色类,用户类,权限类)要记得实现Serializable接口

    最后在Shiro配置类中开启缓存,使用我们自己定义的RedisManager

     @Bean
    public Realm getRealm() {
    CustomRelam customRelam = new CustomRelam();
    // 创建校验匹配器
    HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
    // 散列1024次
    hashedCredentialsMatcher.setHashIterations(1024);
    // 加密算法是MD5
    hashedCredentialsMatcher.setHashAlgorithmName("md5");
    customRelam.setCredentialsMatcher(hashedCredentialsMatcher); // 开启全局缓存
    customRelam.setCachingEnabled(true);
    // 开启认证缓存
    customRelam.setAuthenticationCachingEnabled(true);
    // 设置认证缓存管理的名字
    customRelam.setAuthenticationCacheName("authenticationCache");
    // 开启授权缓存管理
    customRelam.setAuthorizationCachingEnabled(true);
    // 设置授权缓存管理的名字
    customRelam.setAuthorizationCacheName("authorizationCache");
    // 开启Redis缓存
    customRelam.setCacheManager(new RedisCacheManager()); return customRelam;
    }

    启动项目,登录用户,第一次会从数据库中查询,并通过RedisTemplate的put方法将用户信息装入缓存,下次再刷新首页就会从redis中查询权限,授权等信息。退出时会调用RedisTemplate中的remove方法清除向对应的用户缓存。

SpringBoot 集成Shiro之使用Redis缓存授权认证信息的更多相关文章

  1. SpringBoot集成Shiro 实现动态加载权限

    一.前言 本文小编将基于 SpringBoot 集成 Shiro 实现动态uri权限,由前端vue在页面配置uri,Java后端动态刷新权限,不用重启项目,以及在页面分配给用户 角色 . 按钮 .ur ...

  2. SpringBoot学习笔记(五):SpringBoot集成lombok工具、SpringBoot集成Shiro安全框架

    SpringBoot集成lombok工具 什么是lombok? 自动生成setget方法,构造函数,打印日志 官网:http://projectlombok.org/features/index. 平 ...

  3. SpringBoot整合Shiro+MD5+Salt+Redis实现认证和动态权限管理|前后端分离(下)----筑基后期

    写在前面 在上一篇文章<SpringBoot整合Shiro+MD5+Salt+Redis实现认证和动态权限管理(上)----筑基中期>当中,我们初步实现了SpringBoot整合Shiro ...

  4. SpringBoot集成Shiro并用MongoDB做Session存储

    之前项目鉴权一直使用的Shiro,那是在Spring MVC里面使用的比较多,而且都是用XML来配置,用Shiro来做权限控制相对比较简单而且成熟,而且我一直都把Shiro的session放在mong ...

  5. SpringBoot整合Shiro+MD5+Salt+Redis实现认证和动态权限管理(上)----筑基中期

    写在前面 通过前几篇文章的学习,我们从大体上了解了shiro关于认证和授权方面的应用.在接下来的文章当中,我将通过一个demo,带领大家搭建一个SpringBoot整合Shiro的一个项目开发脚手架, ...

  6. SpringBoot集成Shiro

    Shiro是一个安全框架,控制登陆,角色权限管理(身份认证.授权.回话管理.加密) Shiro不会去维护用户,维护权限:这些需要通过realm让开发人员自己注入 1.在pom.xml中引入shiro的 ...

  7. springboot集成shiro实现权限认证

    github:https://github.com/peterowang/shiro 基于上一篇:springboot集成shiro实现身份认证 1.加入UserController package ...

  8. spring-boot集成mybatis,用redis做缓存

    网上有很多例子了,执行源码起码有3个,都是各种各样的小问题. 现在做了个小demo,实现spring-boot 用redis做缓存的实例,简单记录下思路,分享下源码. 缓存的实现,分担了数据库的压力, ...

  9. SpringBoot集成Shiro安全框架

    跟着我的步骤:先运行起来再说 Spring集成Shiro的GitHub:https://github.com/yueshutong/shiro-imooc 一:导包 <!-- Shiro安全框架 ...

随机推荐

  1. golang omitempty 总结

    golang omitempty 总结 在使用Golang的时候,不免会使用Json和结构体的相互转换,这时候常用的就是 json.Marshal和json.Unmarshal两个函数. 这时候在定义 ...

  2. linux 下指定配置文件安装mongodb

    下载 官网下载地址:https://www.mongodb.com/try/download/community,并上传linux 服务器 二.mongon目录结构下 /data/mongo . lo ...

  3. matplotlib的学习4-设置坐标轴

    import matplotlib.pyplot as plt import numpy as np x = np.linspace(-3, 3, 50) y1 = 2*x + 1 y2 = x**2 ...

  4. DRF比Django的认证和权限高在哪里

    Django可以用LoginRequiredMixin和PermissionRequiredMixin给类视图添加认证和权限,DRF做了高级封装,提供了更简洁的实现方式.我们通过继续学习官网教程来进行 ...

  5. dropload.min.js 下拉刷新后,无法上拉加载更多

    使用方法 1.引入文件 <script src="/app/media/js/dropload.min.js"></script> 111111111111 ...

  6. luabind 使用

    LuaBind --最强大的Lua C++ Bind 转载:http://www.cppblog.com/deane/articles/49208.html1 介绍LuaBind 是一个帮助你绑定C+ ...

  7. 说说 Python 中的高阶函数

    高阶函数(higher-order function)指的是:接受一个函数为参数,或者把函数作为结果值返回的函数. 1 sorted() 比较常见的高阶函数是 sorted(),其内部的关键字参数 k ...

  8. IIS放置的APP安装包在浏览器无法打开

    无法打开的提示   操作步骤 1.将APP安装包放置到指定的文件夹中. 2.在IIS中MIME中添加MIME类型 扩展名:.apk MIME类型:application/vnd.android.pac ...

  9. 李宏毅机器学习课程笔记-2.5线性回归Python实战

    本文为作者学习李宏毅机器学习课程时参照样例完成homework1的记录. 任务描述(Task Description) 现在有某地空气质量的观测数据,请使用线性回归拟合数据,预测PM2.5. 数据集描 ...

  10. java中使用IO流将以文件中的内容去取到指定的文件中

    public class Demo12 { public static void main(String[] args) throws IOException { File file=new File ...