七、SpringBoot缓存之EhCache
1、Cache作用
-
Cachehu缓存:计算机内存中一段数据
-
作用:用来减轻DB的访问压力,从而提高系统的查询效率
-
流程:
2、使用shiro中默认的EhCache实现缓存
引入依赖
<!--引入shiro和ehcache-->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-ehcache</artifactId>
<version>1.5.3</version>
</dependency>
修改ShiroConfig
package com.hz52.springboot_jsp_shiro.config;
import com.hz52.springboot_jsp_shiro.shiro.realms.CustomerRealm;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.cache.ehcache.EhCacheManager;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.HashMap;
import java.util.Map;
/**
* @Program: springboot_jsp_shiro
* @Description: 用来整合shiro相关配置类
* @Author: 52Hz
* @CreationTime: 2021年10月20日 9:18 星期三
**/
@Configuration
public class ShiroConfig {
//1、shiroFilter //负责拦截所有请求(依赖2)
@Bean
public ShiroFilterFactoryBean getShiroFilterFactoryBean(DefaultWebSecurityManager defaultWebSecurityManager) {
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
//给filter设置安全管理器
shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);
//配置系统受限资源
Map<String, String> map = new HashMap<String, String>();
map.put("/user/login", "anon"); //anon设置为公共资源
map.put("/user/register", "anon"); //anon设置为公共资源
map.put("/register.jsp", "anon"); //anon设置为公共资源
map.put("/**", "authc"); //authc请求这个资源需要认证和授权
shiroFilterFactoryBean.setFilterChainDefinitionMap(map);
//默认认证界面路径
shiroFilterFactoryBean.setLoginUrl("/login.jsp");
//配置系统公共资源
return shiroFilterFactoryBean;
}
//2、创建安全管理器(依赖3)
@Bean
public DefaultWebSecurityManager getDefaultWebSecurityManager(Realm realm) {
DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
//给安全管理器设置
defaultWebSecurityManager.setRealm(realm);
return defaultWebSecurityManager;
}
//3、创建自定义realm(依赖Realms里面的自定义realm)
@Bean
public Realm getRealm() {
CustomerRealm customerRealm = new CustomerRealm();
//修改密码匹配器:默认最简单
HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher();
//设置加密算法为md5
credentialsMatcher.setHashAlgorithmName("md5");
//设置散列次数
credentialsMatcher.setHashIterations(1024);
customerRealm.setCredentialsMatcher(credentialsMatcher);
//2021/10/23 14:53 开启缓存管理-start
//1、指定缓存管理器
customerRealm.setCacheManager(new EhCacheManager());
//2、开启全局缓存(依赖1)
customerRealm.setCachingEnabled(true);
//3、开启认证缓存(依赖2)
customerRealm.setAuthenticationCachingEnabled(true);
//在内存中起名(非必要)
customerRealm.setAuthenticationCacheName("authenticationCache");
//3、开启授权缓存(依赖2)
customerRealm.setAuthorizationCachingEnabled(true);
//在内存中起名(非必要)
customerRealm.setAuthorizationCacheName("authorizationCache");
//2021/10/23 14:53 开启缓存管理-end
return customerRealm;
}
}
测试
第一次认证会查询,之后不会查询