SpringBoot中Shiro缓存使用Redis、Ehcache的方法
SpringBoot中配置redis作为session缓存器。让shiro引用
本文是建立在你是使用这shiro基础之上的补充内容
第一种:Redis缓存,将数据存储到redis并且开启session存入redis中。
引入pom
org.springframework.boot spring-boot-starter-data-redis org.springframework.session spring-session-data-redis
配置redisConfig
@Configuration @EnableCaching publicclassRedisConfigextendsCachingConfigurerSupport{ @Bean publicKeyGeneratorkeyGenerator(){ returnnewKeyGenerator(){ @Override publicObjectgenerate(Objecttarget,Methodmethod,Object...params){ StringBuildersb=newStringBuilder(); sb.append(target.getClass().getName()); sb.append(method.getName()); for(Objectobj:params){ sb.append(obj.toString()); } returnsb.toString(); } }; } @Bean //在这里配置缓存reids配置 publicRedisCacheManagercacheManager(RedisConnectionFactoryredisConnectionFactory){ RedisCacheConfigurationredisCacheConfiguration=RedisCacheConfiguration.defaultCacheConfig() .entryTtl(Duration.ofHours(1));//设置缓存有效期一小时 System.out.println("《========【开启redis】========》"); returnRedisCacheManager .builder(RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory)) .cacheDefaults(redisCacheConfiguration).build(); } @Bean publicRedisTemplateredisTemplate(RedisConnectionFactoryfactory){ StringRedisTemplatetemplate=newStringRedisTemplate(factory); Jackson2JsonRedisSerializerjackson2JsonRedisSerializer=newJackson2JsonRedisSerializer(Object.class); ObjectMapperom=newObjectMapper(); om.setVisibility(PropertyAccessor.ALL,JsonAutoDetect.Visibility.ANY); om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); jackson2JsonRedisSerializer.setObjectMapper(om); template.setValueSerializer(jackson2JsonRedisSerializer); template.afterPropertiesSet(); returntemplate; } }
配置自定义缓存管理器,引入redis缓存管理器
定义自己的CacheManager
/** *自定义cacheManage扩张shiro里面的缓存使用reids作缓存
**引入自己定义的CacheManager *关于CacheManager的配置文件在spring-redis-cache.xml中 * */ @Component publicclassShiroSpringCacheManagerimplementsCacheManager,Destroyable{ /** *将之上的RedisCacheManager的Bean拿出来注入于此 */ @Autowired privateorg.springframework.cache.CacheManagercacheManager; publicorg.springframework.cache.CacheManagergetCacheManager(){ returncacheManager; } publicvoidsetCacheManager(org.springframework.cache.CacheManagercacheManager){ this.cacheManager=cacheManager; } @Override publicvoiddestroy()throwsException{ cacheManager=null; } @Override publicCache getCache(Stringname){ if(name==null){ returnnull; } //新建一个ShiroSpringCache将Bean放入并实例化 returnnewShiroSpringCache (name,getCacheManager()); } }
定义自己实现的Shiro的Cache,实现了Shiro包里的Cache
/** *自定义缓存将数据存入到redis中
*/ @SuppressWarnings("unchecked") publicclassShiroSpringCacheimplementsorg.apache.shiro.cache.Cache { privatestaticfinalLoggerlog=LoggerFactory.getLogger(ShiroSpringCache.class); privateCacheManagercacheManager; privateCachecache; publicShiroSpringCache(Stringname,CacheManagercacheManager){ if(name==null||cacheManager==null){ thrownewIllegalArgumentException("cacheManagerorCacheNamecannotbenull."); } this.cacheManager=cacheManager; //这里首先是从父类中获取这个cache,如果没有会创建一个redisCache,初始化这个redisCache的时候 //会设置它的过期时间如果没有配置过这个缓存的,那么默认的缓存时间是为0的,如果配置了,就会把配置的时间赋予给这个RedisCache //如果从缓存的过期时间为0,就表示这个RedisCache不存在了,这个redisCache实现了spring中的cache this.cache=cacheManager.getCache(name); } @Override publicVget(Kkey)throwsCacheException{ log.info("从缓存中获取key为{}的缓存信息",key); if(key==null){ returnnull; } ValueWrappervalueWrapper=cache.get(key); if(valueWrapper==null){ returnnull; } return(V)valueWrapper.get(); } @Override publicVput(Kkey,Vvalue)throwsCacheException{ log.info("创建新的缓存,信息为:{}={}",key,value); cache.put(key,value); returnget(key); } @Override publicVremove(Kkey)throwsCacheException{ log.info("干掉key为{}的缓存",key); Vv=get(key); cache.evict(key);//干掉这个名字为key的缓存 returnv; } @Override publicvoidclear()throwsCacheException{ log.info("清空所有的缓存"); cache.clear(); } @Override publicintsize(){ returncacheManager.getCacheNames().size(); } /** *获取缓存中所的key值 */ @Override publicSet keys(){ return(Set )cacheManager.getCacheNames(); } /** *获取缓存中所有的values值 */ @Override publicCollection values(){ return(Collection )cache.get(cacheManager.getCacheNames()).get(); } @Override publicStringtoString(){ return"ShiroSpringCache[cache="+cache+"]"; } }
到此为止,使用redis做缓存,和spring的集成就完成了。
可以使用以下注解将缓存放入redis
@Cacheable(value=Cache.CONSTANT,key="'"+CacheKey.DICT_NAME+"'+#name+'_'+#val")
配置springsession管理器
@Bean @ConditionalOnProperty(prefix="xpro",name="spring-session-open",havingValue="true") publicServletContainerSessionManagerservletContainerSessionManager(){ returnnewServletContainerSessionManager(); }
新建类springsession设置session过期时间
/** *springsession配置 * *@authorxingri *@date2017-07-1321:05 */ @EnableRedisHttpSession(maxInactiveIntervalInSeconds=900)//session过期时间如果部署多机环境,需要打开注释 @ConditionalOnProperty(prefix="xpro",name="spring-session-open",havingValue="true") publicclassSpringSessionConfig{ }
第一种:Ehcache做缓存,可以将数据存储到磁盘中,也可以存到内存中
新建ehcache.xml文件
配置自定义缓存管理器,引入ehcache缓存管理器
/** *ehcache配置 * */ @Configuration @EnableCaching publicclassEhCacheConfig{ /** *EhCache的配置 */ @Bean publicEhCacheCacheManagercacheManager(CacheManagercacheManager){ MBeanServermBeanServer=ManagementFactory.getPlatformMBeanServer(); ManagementService.registerMBeans(cacheManager,mBeanServer,true,true,true,true); returnnewEhCacheCacheManager(cacheManager); } /** *EhCache的配置 */ @Bean publicEhCacheManagerFactoryBeanehcache(){ System.out.println("《========【开启ehcache】========》"); EhCacheManagerFactoryBeanehCacheManagerFactoryBean=newEhCacheManagerFactoryBean(); ehCacheManagerFactoryBean.setConfigLocation(newClassPathResource("ehcache.xml")); returnehCacheManagerFactoryBean; } @Bean publicorg.apache.shiro.cache.CacheManagergetCacheShiroManager(EhCacheManagerFactoryBeanehcache){ EhCacheManagerehCacheManager=newEhCacheManager(); ehCacheManager.setCacheManager(ehcache.getObject()); returnehCacheManager; } }
最后最重要的是引入shriro中
/** *shiro权限管理的配置 * */ @Configuration publicclassShiroConfig{ /** *安全管理器 */ @Bean publicDefaultWebSecurityManagersecurityManager(CookieRememberMeManagerrememberMeManager,CacheManagercacheShiroManager,SessionManagersessionManager){ DefaultWebSecurityManagersecurityManager=newDefaultWebSecurityManager(); securityManager.setAuthenticator(modularRealmAuthenticator()); Listrealms=newArrayList<>(); securityManager.setRealms(realms); securityManager.setCacheManager(cacheShiroManager); securityManager.setRememberMeManager(rememberMeManager); securityManager.setSessionManager(sessionManager); returnsecurityManager; } /** *springsession管理器(多机环境) */ @Bean publicServletContainerSessionManagerservletContainerSessionManager(){ returnnewServletContainerSessionManager(); } /** *session管理器(单机环境)使用cookie存储缓存。。如果多级请注释 */ @Bean publicDefaultWebSessionManagerdefaultWebSessionManager(CacheManagercacheShiroManager,XProPropertiesxProProperties){ DefaultWebSessionManagersessionManager=newDefaultWebSessionManager(); sessionManager.setCacheManager(cacheShiroManager); sessionManager.setSessionValidationInterval(xProProperties.getSessionValidationInterval()*1000); sessionManager.setGlobalSessionTimeout(xProProperties.getSessionInvalidateTime()*1000); sessionManager.setDeleteInvalidSessions(true); sessionManager.setSessionValidationSchedulerEnabled(true); Cookiecookie=newSimpleCookie(ShiroHttpSession.DEFAULT_SESSION_ID_NAME); cookie.setName("shiroCookie"); cookie.setHttpOnly(true); sessionManager.setSessionIdCookie(cookie); returnsessionManager; } /** *缓存管理器使用Ehcache实现如果使用redis则注释下面内容!!!! */ @Bean publicCacheManagergetCacheShiroManager(EhCacheManagerFactoryBeanehcache){ EhCacheManagerehCacheManager=newEhCacheManager(); ehCacheManager.setCacheManager(ehcache.getObject()); returnehCacheManager; } /** *项目自定义的Realm */ @Bean publicShiroDbRealmshiroDbRealm(){ returnnewShiroDbRealm(); } @Bean publicShiroTockenRealmshiroTockenRealm(){ returnnewShiroTockenRealm(); } @Bean publicShiroJwtRealmshiroJwtRealm(){ returnnewShiroJwtRealm(); } /** *系统自带的Realm管理,主要针对多realm **/ @Bean publicModularRealmAuthenticatormodularRealmAuthenticator(){ ModularRealmAuthenticatormodularRealmAuthenticator=newModularRealmAuthenticator(); modularRealmAuthenticator.setAuthenticationStrategy(newAtLeastOneSuccessfulStrategy()); returnmodularRealmAuthenticator; } /** *rememberMe管理器,cipherKey生成见{@codeBase64Test.java} */ @Bean publicCookieRememberMeManagerrememberMeManager(SimpleCookierememberMeCookie){ CookieRememberMeManagermanager=newCookieRememberMeManager(); manager.setCipherKey(Base64.decode("Z3VucwAAAAAAAAAAAAAAAA==")); manager.setCookie(rememberMeCookie); returnmanager; } /** *记住密码Cookie */ @Bean publicSimpleCookierememberMeCookie(){ SimpleCookiesimpleCookie=newSimpleCookie("rememberMe"); simpleCookie.setHttpOnly(true); simpleCookie.setMaxAge(7*24*60*60);//7天 returnsimpleCookie; } /** *在方法中注入securityManager,进行代理控制 */ @Bean publicMethodInvokingFactoryBeanmethodInvokingFactoryBean(DefaultWebSecurityManagersecurityManager){ MethodInvokingFactoryBeanbean=newMethodInvokingFactoryBean(); bean.setStaticMethod("org.apache.shiro.SecurityUtils.setSecurityManager"); bean.setArguments(newObject[]{securityManager}); returnbean; } /** *保证实现了Shiro内部lifecycle函数的bean执行 */ @Bean publicLifecycleBeanPostProcessorlifecycleBeanPostProcessor(){ returnnewLifecycleBeanPostProcessor(); } /** *启用shrio授权注解拦截方式,AOP式方法级权限检查 */ @Bean @DependsOn(value="lifecycleBeanPostProcessor")//依赖其他bean的初始化 publicDefaultAdvisorAutoProxyCreatordefaultAdvisorAutoProxyCreator(){ returnnewDefaultAdvisorAutoProxyCreator(); } @Bean publicAuthorizationAttributeSourceAdvisorauthorizationAttributeSourceAdvisor(DefaultWebSecurityManagersecurityManager){ AuthorizationAttributeSourceAdvisorauthorizationAttributeSourceAdvisor= newAuthorizationAttributeSourceAdvisor(); authorizationAttributeSourceAdvisor.setSecurityManager(securityManager); returnauthorizationAttributeSourceAdvisor; } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。