沫言|java:shiro高级篇——1
第六章Realm缓存机制1、Realm缓存机制意义在上面我们自定了自己的realm , 但是我们发现
3、redission集成【1】添加shiroRedisProperties此类主要负责yaml文件的配置类
packagecom.itheima.shiro.config;importlombok.Data;importorg.springframework.boot.context.properties.ConfigurationProperties;importjava.io.Serializable;/***@Descriptionredis配置文件*/@Data@ConfigurationProperties(prefix="itheima.framework.shiro.redis")publicclassShiroRedisPropertiesimplementsSerializable{/***redis连接地址*/privateStringnodes;/***获取连接超时时间*/privateintconnectTimeout;/***连接池大小*/privateintconnectPoolSize;/***初始化连接数*/privateintconnectionMinimumidleSize;/***等待数据返回超时时间*/privateinttimeout;/***全局超时时间*/privatelongglobalSessionTimeout;}【2】编辑ShiroConfig集成redisson的相关配置 , 同时启用ShiroRedisProperties的配置
packagecom.itheima.shiro.config;importcom.itheima.shiro.core.ShiroDbRealm;importcom.itheima.shiro.core.impl.ShiroDbRealmImpl;importcom.itheima.shiro.filter.RolesOrAuthorizationFilter;importcom.itheima.shiro.properties.PropertiesUtil;importlombok.extern.log4j.Log4j2;importorg.apache.shiro.spring.LifecycleBeanPostProcessor;importorg.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;importorg.apache.shiro.spring.web.ShiroFilterFactoryBean;importorg.apache.shiro.web.mgt.DefaultWebSecurityManager;importorg.apache.shiro.web.servlet.SimpleCookie;importorg.apache.shiro.web.session.mgt.DefaultWebSessionManager;importorg.redisson.Redisson;importorg.redisson.api.RedissonClient;importorg.redisson.config.Config;importorg.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.boot.context.properties.EnableConfigurationProperties;importorg.springframework.context.annotation.Bean;importorg.springframework.context.annotation.ComponentScan;importorg.springframework.context.annotation.Configuration;importorg.springframework.context.annotation.DependsOn;importjavax.servlet.Filter;importjava.util.HashMap;importjava.util.LinkedHashMap;importjava.util.List;importjava.util.Map;/***@Description权限配置类*/@Configuration@ComponentScan(basePackages="com.itheima.shiro.core")@EnableConfigurationProperties({ShiroRedisProperties.class})@Log4j2publicclassShiroConfig{@AutowiredprivateShiroRedisPropertiesshiroRedisProperties;/***@Descriptionredission客户端*/@Bean("redissonClientForShiro")publicRedissonClientredissonClient(){log.info("=====初始化redissonClientForShiro开始======");String[]nodeList=shiroRedisProperties.getNodes().split(",");Configconfig=newConfig();if(nodeList.length==1){config.useSingleServer().setAddress(nodeList[0]).setConnectTimeout(shiroRedisProperties.getConnectTimeout()).setConnectionMinimumIdleSize(shiroRedisProperties.getConnectionMinimumidleSize()).setConnectionPoolSize(shiroRedisProperties.getConnectPoolSize()).setTimeout(shiroRedisProperties.getTimeout());}else{config.useClusterServers().addNodeAddress(nodeList).setConnectTimeout(shiroRedisProperties.getConnectTimeout()).setMasterConnectionMinimumIdleSize(shiroRedisProperties.getConnectionMinimumidleSize()).setMasterConnectionPoolSize(shiroRedisProperties.getConnectPoolSize()).setTimeout(shiroRedisProperties.getTimeout());}RedissonClientredissonClient=Redisson.create(config);log.info("=====初始化redissonClientForShiro完成======");returnredissonClient;}/***@Description创建cookie对象*/@Bean(name="sessionIdCookie")publicSimpleCookiesimpleCookie(){SimpleCookiesimpleCookie=newSimpleCookie();simpleCookie.setName("ShiroSession");returnsimpleCookie;}/***@Description权限管理器*@param*@return*/@Bean(name="securityManager")publicDefaultWebSecurityManagerdefaultWebSecurityManager(){DefaultWebSecurityManagersecurityManager=newDefaultWebSecurityManager();securityManager.setRealm(shiroDbRealm());securityManager.setSessionManager(shiroSessionManager());returnsecurityManager;}/***@Description自定义RealmImpl*/@Bean(name="shiroDbRealm")publicShiroDbRealmshiroDbRealm(){returnnewShiroDbRealmImpl();}/***@Description会话管理器*/@Bean(name="sessionManager")publicDefaultWebSessionManagershiroSessionManager(){DefaultWebSessionManagersessionManager=newDefaultWebSessionManager();sessionManager.setSessionValidationSchedulerEnabled(false);sessionManager.setSessionIdCookieEnabled(true);sessionManager.setSessionIdCookie(simpleCookie());sessionManager.setGlobalSessionTimeout(3600000);returnsessionManager;}/***@Description保证实现了Shiro内部lifecycle函数的bean执行*/@Bean(name="lifecycleBeanPostProcessor")publicstaticLifecycleBeanPostProcessorgetLifecycleBeanPostProcessor(){returnnewLifecycleBeanPostProcessor();}/***@DescriptionAOP式方法级权限检查*/@Bean@DependsOn("lifecycleBeanPostProcessor")publicDefaultAdvisorAutoProxyCreatorgetDefaultAdvisorAutoProxyCreator(){DefaultAdvisorAutoProxyCreatordefaultAdvisorAutoProxyCreator=newDefaultAdvisorAutoProxyCreator();defaultAdvisorAutoProxyCreator.setProxyTargetClass(true);returndefaultAdvisorAutoProxyCreator;}/***@Description配合DefaultAdvisorAutoProxyCreator事项注解权限校验*/@BeanpublicAuthorizationAttributeSourceAdvisorgetAuthorizationAttributeSourceAdvisor(){AuthorizationAttributeSourceAdvisoraasa=newAuthorizationAttributeSourceAdvisor();aasa.setSecurityManager(defaultWebSecurityManager());returnnewAuthorizationAttributeSourceAdvisor();}/***@Description过滤器链*/privateMapfilterChainDefinition(){Listlist=PropertiesUtil.propertiesShiro.getKeyList();Mapmap=newLinkedHashMap<>();for(Objectobject:list){Stringkey=object.toString();Stringvalue=https://pcff.toutiao.jxnews.com.cn/p/20200804/PropertiesUtil.getShiroValue(key);log.info("读取防止盗链控制:---key{},---value:{}",key,value);map.put(key,value);}returnmap;}/***@Description自定义过滤器定义*/privateMapfilters(){Mapmap=newHashMap();map.put("roleOr",newRolesOrAuthorizationFilter());returnmap;}/***@DescriptionShiro过滤器*/@Bean("shiroFilter")publicShiroFilterFactoryBeanshiroFilterFactoryBean(){ShiroFilterFactoryBeanshiroFilter=newShiroFilterFactoryBean();shiroFilter.setSecurityManager(defaultWebSecurityManager());//使自定义过滤器生效shiroFilter.setFilters(filters());shiroFilter.setFilterChainDefinitionMap(filterChainDefinition());shiroFilter.setLoginUrl("/login");shiroFilter.setUnauthorizedUrl("/login");returnshiroFilter;}}4、缓存对象SimpleMapCachepackagecom.itheima.shiro.core.base;importcom.itheima.shiro.utils.EmptyUtil;importorg.apache.shiro.cache.Cache;importorg.apache.shiro.cache.CacheException;importjava.io.Serializable;importjava.util.Collection;importjava.util.Collections;importjava.util.Map;importjava.util.Set;/***@Description缓存实现类,实现序列接口方便对象存储于第三方容器(Map存放键值对)*/publicclassSimpleMapCacheimplementsCache,Serializable{privatefinalMapattributes;privatefinalStringname;publicSimpleMapCache(Stringname,MapbackingMap){if(name==null)thrownewIllegalArgumentException("Cachenamecannotbenull.");if(backingMap==null){thrownewIllegalArgumentException("Backingmapcannotbenull.");}else{this.name=name;attributes=backingMap;}}publicObjectget(Objectkey)throwsCacheException{returnattributes.get(key);}publicObjectput(Objectkey,Objectvalue)throwsCacheException{returnattributes.put(key,value);}publicObjectremove(Objectkey)throwsCacheException{returnattributes.remove(key);}publicvoidclear()throwsCacheException{attributes.clear();}publicintsize(){returnattributes.size();}publicSetkeys(){Setkeys=attributes.keySet();if(!keys.isEmpty())returnCollections.unmodifiableSet(keys);elsereturnCollections.emptySet();}publicCollectionvalues(){Collectionvalues=attributes.values();if(!EmptyUtil.isNullOrEmpty(values))returnCollections.unmodifiableCollection(values);elsereturnCollections.emptySet();}@OverridepublicStringtoString(){return"SimpleMapCache[attributes="+attributes+",name="+name+",keys()="+keys()+",size()="+size()+",values()="+values()+"]";}}5、ShiroRedissionSerialize序列化工具packagecom.itheima.shiro.utils;importlombok.extern.log4j.Log4j2;importorg.apache.shiro.codec.Base64;importjava.io.*;/***@Description:实现shiro会话的序列化存储*/@Log4j2publicclassShiroRedissionSerialize{publicstaticObjectdeserialize(Stringstr){if(EmptyUtil.isNullOrEmpty(str)){returnnull;}ByteArrayInputStreambis=null;ObjectInputStreamois=null;Objectobject=null;try{bis=newByteArrayInputStream(EncodesUtil.decodeBase64(str));ois=newObjectInputStream(bis);object=ois.readObject();}catch(IOException|ClassNotFoundExceptione){log.error("流读取异常:{}",e);}finally{try{bis.close();ois.close();}catch(IOExceptione){log.error("流读取异常:{}",e);}}returnobject;}publicstaticStringserialize(Objectobj){if(EmptyUtil.isNullOrEmpty(obj)){returnnull;}ByteArrayOutputStreambos=null;ObjectOutputStreamoos=null;Stringbase64String=null;try{bos=newByteArrayOutputStream();oos=newObjectOutputStream(bos);oos.writeObject(obj);base64String=EncodesUtil.encodeBase64(bos.toByteArray());}catch(IOExceptione){log.error("流写入异常:{}",e);}finally{try{bos.close();oos.close();}catch(IOExceptione){log.error("流写入异常:{}",e);}}returnbase64String;}}6、缓存服务接口SimpleCacheServiceSimpleCacheService
- Java|计算机专业的本科生,该选择学习Java技术体系还是.NET技术体系
- 小熊回收站|-链表阻塞队列和数组阻塞队列的异同,Java并发编程
- Java|马化腾登顶中国首富,微信、QQ却都免费使用,腾讯到底咋赚钱的?
- Java|为什么美团骑手总是闯红灯昵
- 沫言|小米100wTypeC扩展坞来了,买苹果本都少不了转接口
- 阿里巴巴|java三大集合遍历方法
- 编程|JAVA基础-网络编程
- 沫言|告别重复劳动,网易后端教你这样做,十小时代码量一小时搞定
- Java|Java中的天使和魔鬼:Unsafe类
- 沫言|预算4K选谁更省心?,国产“三剑客”受学生党追捧