在SpringBoot中Shiro缓存使用Redis、Ehcache实现的两种方式实例 SpringBoot 中配置redis作为session 缓存器。 让shiro引用
本文是建立在你是使用这shiro基础之上的补充内容
第一种:Redis缓存,将数据存储到redis 并且开启session存入redis中。 引入pom 1 2 3 4 5 6 7 8 <dependency > <groupId > org.springframework.boot</groupId > <artifactId > spring-boot-starter-data-redis</artifactId > </dependency > <dependency > <groupId > org.springframework.session</groupId > <artifactId > spring-session-data-redis</artifactId > </dependency >
配置redisConfig 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 @Configuration @EnableCaching public class RedisConfig extends CachingConfigurerSupport { @Bean public KeyGenerator keyGenerator () { return new KeyGenerator() { @Override public Object generate (Object target, Method method, Object... params) { StringBuilder sb = new StringBuilder(); sb.append(target.getClass().getName()); sb.append(method.getName()); for (Object obj : params) { sb.append(obj.toString()); } return sb.toString(); } }; } @Bean public RedisCacheManager cacheManager (RedisConnectionFactory redisConnectionFactory) { RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig() .entryTtl(Duration.ofHours(1 )); System.out.println("《========【开启redis】 ======== 》 " ); return RedisCacheManager .builder(RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory)) .cacheDefaults(redisCacheConfiguration).build(); } @Bean public RedisTemplate<String, String> redisTemplate (RedisConnectionFactory factory) { StringRedisTemplate template = new StringRedisTemplate(factory); Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class); ObjectMapper om = new ObjectMapper(); om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); jackson2JsonRedisSerializer.setObjectMapper(om); template.setValueSerializer(jackson2JsonRedisSerializer); template.afterPropertiesSet(); return template; } }
配置自定义缓存管理器,引入redis缓存管理器
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 @Component public class ShiroSpringCacheManager implements CacheManager ,Destroyable { @Autowired private org.springframework.cache.CacheManager cacheManager; public org.springframework.cache.CacheManager getCacheManager () { return cacheManager; } public void setCacheManager (org.springframework.cache.CacheManager cacheManager) { this .cacheManager = cacheManager; } @Override public void destroy () throws Exception { cacheManager = null ; } @Override public <K, V> Cache<K, V> getCache (String name) { if (name == null ){ return null ; } return new ShiroSpringCache<K,V>(name,getCacheManager()); } }
定义自己实现的Shiro的Cache,实现了Shiro包里的Cache
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 @SuppressWarnings("unchecked") public class ShiroSpringCache <K ,V > implements org .apache .shiro .cache .Cache <K , V > { private static final Logger log = LoggerFactory.getLogger(ShiroSpringCache.class); private CacheManager cacheManager; private Cache cache; public ShiroSpringCache (String name, CacheManager cacheManager) { if (name==null || cacheManager==null ){ throw new IllegalArgumentException("cacheManager or CacheName cannot be null." ); } this .cacheManager = cacheManager; this .cache= cacheManager.getCache(name); } @Override public V get (K key) throws CacheException { log.info("从缓存中获取key为{}的缓存信息" ,key); if (key == null ){ return null ; } ValueWrapper valueWrapper = cache.get(key); if (valueWrapper==null ){ return null ; } return (V) valueWrapper.get(); } @Override public V put (K key, V value) throws CacheException { log.info("创建新的缓存,信息为:{}={}" ,key,value); cache.put(key, value); return get(key); } @Override public V remove (K key) throws CacheException { log.info("干掉key为{}的缓存" ,key); V v = get(key); cache.evict(key); return v; } @Override public void clear () throws CacheException { log.info("清空所有的缓存" ); cache.clear(); } @Override public int size () { return cacheManager.getCacheNames().size(); } @Override public Set<K> keys () { return (Set<K>) cacheManager.getCacheNames(); } @Override public Collection<V> values () { return (Collection<V>) cache.get(cacheManager.getCacheNames()).get(); } @Override public String toString () { return "ShiroSpringCache [cache=" + cache + "]" ; } }
1 @Cacheable(value = Cache.CONSTANT, key = "'" + CacheKey.DICT_NAME + "'+#name+'_'+#val")
配置spring session管理器 1 2 3 4 5 @Bean @ConditionalOnProperty(prefix = "xpro", name = "spring-session-open", havingValue = "true") public ServletContainerSessionManager servletContainerSessionManager() { return new ServletContainerSessionManager(); }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 <?xml version="1.0" encoding="UTF-8"?> <ehcache updateCheck ="false" dynamicConfig ="false" > <diskStore path ="java.io.tmpdir" /> <cache name ="authorizationCache" maxEntriesLocalHeap ="2000" eternal ="false" timeToIdleSeconds ="1800" timeToLiveSeconds ="1800" overflowToDisk ="false" statistics ="true" > </cache > <cache name ="authenticationCache" maxEntriesLocalHeap ="2000" eternal ="false" timeToIdleSeconds ="1800" timeToLiveSeconds ="1800" overflowToDisk ="false" statistics ="true" > </cache > <cache name ="activeSessionCache" maxEntriesLocalHeap ="2000" eternal ="false" timeToIdleSeconds ="1800" timeToLiveSeconds ="1800" overflowToDisk ="false" statistics ="true" > </cache > <cache name ="halfHour" maxElementsInMemory ="10000" maxElementsOnDisk ="100000" eternal ="false" timeToIdleSeconds ="1800" timeToLiveSeconds ="1800" overflowToDisk ="false" diskPersistent ="false" /> <cache name ="hour" maxElementsInMemory ="10000" maxElementsOnDisk ="100000" eternal ="false" timeToIdleSeconds ="3600" timeToLiveSeconds ="3600" overflowToDisk ="false" diskPersistent ="false" /> <cache name ="oneDay" maxElementsInMemory ="10000" maxElementsOnDisk ="100000" eternal ="false" timeToIdleSeconds ="86400" timeToLiveSeconds ="86400" overflowToDisk ="false" diskPersistent ="false" /> <defaultCache name ="defaultCache" maxElementsInMemory ="10000" eternal ="false" timeToIdleSeconds ="600" timeToLiveSeconds ="600" overflowToDisk ="false" maxElementsOnDisk ="100000" diskPersistent ="false" diskExpiryThreadIntervalSeconds ="120" memoryStoreEvictionPolicy ="LRU" /> </ehcache >
配置自定义缓存管理器,引入ehcache缓存管理器 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 @Configuration @EnableCaching public class EhCacheConfig { @Bean public EhCacheCacheManager cacheManager (CacheManager cacheManager) { MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer(); ManagementService.registerMBeans(cacheManager, mBeanServer, true , true , true , true ); return new EhCacheCacheManager(cacheManager); } @Bean public EhCacheManagerFactoryBean ehcache () { System.out.println("《========【开启ehcache】 ======== 》 " ); EhCacheManagerFactoryBean ehCacheManagerFactoryBean = new EhCacheManagerFactoryBean(); ehCacheManagerFactoryBean.setConfigLocation(new ClassPathResource("ehcache.xml" )); return ehCacheManagerFactoryBean; } @Bean public org.apache.shiro.cache.CacheManager getCacheShiroManager (EhCacheManagerFactoryBean ehcache) { EhCacheManager ehCacheManager = new EhCacheManager(); ehCacheManager.setCacheManager(ehcache.getObject()); return ehCacheManager; } }
最后 最重要的是引入shriro 中 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 @Configuration public class ShiroConfig { @Bean public DefaultWebSecurityManager securityManager (CookieRememberMeManager rememberMeManager, CacheManager cacheShiroManager, SessionManager sessionManager) { DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager(); securityManager.setAuthenticator(modularRealmAuthenticator()); List<Realm> realms=new ArrayList<>(); securityManager.setRealms(realms); securityManager.setCacheManager(cacheShiroManager); securityManager.setRememberMeManager(rememberMeManager); securityManager.setSessionManager(sessionManager); return securityManager; } @Bean public ServletContainerSessionManager servletContainerSessionManager () { return new ServletContainerSessionManager(); } @Bean public DefaultWebSessionManager defaultWebSessionManager (CacheManager cacheShiroManager, XProProperties xProProperties) { DefaultWebSessionManager sessionManager = new DefaultWebSessionManager(); sessionManager.setCacheManager(cacheShiroManager); sessionManager.setSessionValidationInterval(xProProperties.getSessionValidationInterval() * 1000 ); sessionManager.setGlobalSessionTimeout(xProProperties.getSessionInvalidateTime() * 1000 ); sessionManager.setDeleteInvalidSessions(true ); sessionManager.setSessionValidationSchedulerEnabled(true ); Cookie cookie = new SimpleCookie(ShiroHttpSession.DEFAULT_SESSION_ID_NAME); cookie.setName("shiroCookie" ); cookie.setHttpOnly(true ); sessionManager.setSessionIdCookie(cookie); return sessionManager; } @Bean public CacheManager getCacheShiroManager (EhCacheManagerFactoryBean ehcache) { EhCacheManager ehCacheManager = new EhCacheManager(); ehCacheManager.setCacheManager(ehcache.getObject()); return ehCacheManager; } @Bean public ShiroDbRealm shiroDbRealm () { return new ShiroDbRealm(); } @Bean public ShiroTockenRealm shiroTockenRealm ( ) { return new ShiroTockenRealm(); } @Bean public ShiroJwtRealm shiroJwtRealm ( ) { return new ShiroJwtRealm(); } @Bean public ModularRealmAuthenticator modularRealmAuthenticator () { ModularRealmAuthenticator modularRealmAuthenticator=new ModularRealmAuthenticator(); modularRealmAuthenticator.setAuthenticationStrategy(new AtLeastOneSuccessfulStrategy()); return modularRealmAuthenticator; } @Bean public CookieRememberMeManager rememberMeManager (SimpleCookie rememberMeCookie) { CookieRememberMeManager manager = new CookieRememberMeManager(); manager.setCipherKey(Base64.decode("Z3VucwAAAAAAAAAAAAAAAA==" )); manager.setCookie(rememberMeCookie); return manager; } @Bean public SimpleCookie rememberMeCookie () { SimpleCookie simpleCookie = new SimpleCookie("rememberMe" ); simpleCookie.setHttpOnly(true ); simpleCookie.setMaxAge(7 * 24 * 60 * 60 ); return simpleCookie; } @Bean public MethodInvokingFactoryBean methodInvokingFactoryBean (DefaultWebSecurityManager securityManager) { MethodInvokingFactoryBean bean = new MethodInvokingFactoryBean(); bean.setStaticMethod("org.apache.shiro.SecurityUtils.setSecurityManager" ); bean.setArguments(new Object[]{securityManager}); return bean; } @Bean public LifecycleBeanPostProcessor lifecycleBeanPostProcessor () { return new LifecycleBeanPostProcessor(); } @Bean @DependsOn(value = "lifecycleBeanPostProcessor") public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator () { return new DefaultAdvisorAutoProxyCreator(); } @Bean public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor (DefaultWebSecurityManager securityManager) { AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor(); authorizationAttributeSourceAdvisor.setSecurityManager(securityManager); return authorizationAttributeSourceAdvisor; } }