springboot②最正確的集成shiro並使用ehcache緩存

springboot集成shiro和ehcache的時候,要先集成ehcache而後再集成shiro,這樣當shiro配置cacheManager的時候就能夠直接使用了。下面是正確的集成步驟:
第一步集成ehcache:
1.在pom.xml文件中引入如下依賴
      <!--開啓 cache 緩存-->
      <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-cache</artifactId>
      </dependency>
      <!-- ehcache 緩存 -->
      <dependency>
          <groupId>net.sf.ehcache</groupId>
          <artifactId>ehcache</artifactId>
      </dependency>
2.引入配置文件 ehcache.xmlcss

ehcache.xml具體內容:
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
         updateCheck="false">
    <defaultCache
            eternal="false"
            maxElementsInMemory="1000"
            overflowToDisk="false"
            diskPersistent="false"
            timeToIdleSeconds="0"
            timeToLiveSeconds="600"
            memoryStoreEvictionPolicy="LRU" />
 
    <!-- 這裏的 users 緩存空間是爲了下面的 demo 作準備 -->
    <cache
            name="users"
            eternal="false"
            maxElementsInMemory="100"
            overflowToDisk="false"
            diskPersistent="false"
            timeToIdleSeconds="0"
            timeToLiveSeconds="300"
            memoryStoreEvictionPolicy="LRU" />
</ehcache>
ehcache.xml 文件配置詳解
部分資料來源於網絡
diskStore:爲緩存路徑,ehcache分爲內存和磁盤兩級,此屬性定義磁盤的緩存位置。
defaultCache:默認緩存策略,當ehcache找不到定義的緩存時,則使用這個緩存策略。只能定義一個。
name:緩存名稱。
maxElementsInMemory:緩存最大數目
maxElementsOnDisk:硬盤最大緩存個數。
eternal:對象是否永久有效,一但設置了,timeout將不起做用。
overflowToDisk:是否保存到磁盤,當系統當機時
timeToIdleSeconds:設置對象在失效前的容許閒置時間(單位:秒)。僅當eternal=false對象不是永久有效時使用,可選屬性,默認值是0,也就是可閒置時間無窮大。
timeToLiveSeconds:設置對象在失效前容許存活時間(單位:秒)。最大時間介於建立時間和失效時間之間。僅當eternal=false對象不是永久有效時使用,默認是0.,也就是對象存活時間無窮大。
diskPersistent:是否緩存虛擬機重啓期數據 Whether the disk store persists between restarts of the Virtual Machine. The default value is false.diskSpoolBufferSizeMB:這個參數設置DiskStore(磁盤緩存)的緩存區大小。默認是30MB。每一個Cache都應該有本身的一個緩衝區。
diskExpiryThreadIntervalSeconds:磁盤失效線程運行時間間隔,默認是120秒。
memoryStoreEvictionPolicy:當達到maxElementsInMemory限制時,Ehcache將會根據指定的策略去清理內存。默認策略是LRU(最近最少使用)。你能夠設置爲FIFO(先進先出)或是LFU(較少使用)。
clearOnFlush:內存數量最大時是否清除。
memoryStoreEvictionPolicy:可選策略有:LRU(最近最少使用,默認策略)、FIFO(先進先出)、LFU(最少訪問次數)。
FIFO,first in first out,先進先出
LFU, Less Frequently Used,一直以來最少被使用的。如上面所講,緩存的元素有一個hit屬性,hit值最小的將會被清出緩存。 
LRU,Least Recently Used,最近最少使用的,緩存的元素有一個時間戳,當緩存容量滿了,而又須要騰出地方來緩存新的元素的時候,那麼現有緩存元素中時間戳離當前時間最遠的元素將被清出緩存。
3.在主類加上啓動註解
在 Spring Boot 主類加上開啓緩存的註解@EnableCaching。
@EnableCaching
@MapperScan(basePackages = "com.tan.dream.**.dao")
@SpringBootApplication
public class DreamApplication {
 
    public static void main(String[] args) {
        SpringApplication.run(DreamApplication.class, args);
    }
}
4.springboot中的緩存註解@Cacheable,@CachePut等就能夠使用了(緩存註解具體使用待完成)
 
重點來了第二步集成shiro並使用ehcache緩存:
1.在pom.xml文件中引入如下依賴
        <!--shiro-->
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-spring</artifactId>
            <version>1.3.2</version>
        </dependency>
        <!-- shiro ehcache -->
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-ehcache</artifactId>
            <version>1.3.2</version>
        </dependency>
2. 編寫shiro的Realm 驗證,固然這是個人shrio的realm,須要根據本身的項目進行一些修改
public class UserRealm extends AuthorizingRealm {
/*    @Autowired
    UserDao userMapper;
    @Autowired
    MenuService menuService;*/
 
    /**
     * 受權
     * @param arg0
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) {
 
        UserDO userDO = (UserDO)SecurityUtils.getSubject().getPrincipal();
        Long userId =  userDO.getUserId();
        MenuService menuService = ApplicationContextRegister.getBean(MenuService.class);
        Set<String> perms = menuService.listPerms(userId);
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setStringPermissions(perms);
        return info;
    }
 
    /** www.1b23.com
     * 認證
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String username = (String) token.getPrincipal();
        Map<String, Object> map = new HashMap<>(16);
        map.put("username", username);
        String password = new String((char[]) token.getCredentials());
 
        UserDao userMapper = ApplicationContextRegister.getBean(UserDao.class);
        // 查詢用戶信息
        UserDO user = userMapper.list(map).get(0);
 
        // 帳號不存在
        if (user == null) {
            throw new UnknownAccountException("帳號或密碼不正確");
        }
 
        // 密碼錯誤
        if (!password.equals(user.getPassword())) {
            throw new IncorrectCredentialsException("帳號或密碼不正確");
        }
 
        // 帳號鎖定
        if (user.getStatus() == 0) {
            throw new LockedAccountException("帳號已被鎖定,請聯繫管理員");
        }
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, password, getName());
        return info;
    }
 
}
3.添加shiro的配置類
@Configuration
public class ShiroConfig {
 
    //@Autowired
    //private CacheManager cacheManager;
 
    @Value("${server.session-timeout}")
    private int tomcatTimeout;
 
    @Bean
    public static LifecycleBeanPostProcessor getLifecycleBeanPostProcessor() {
        return new LifecycleBeanPostProcessor();
    }
 
    /**
     * ShiroDialect,爲了在thymeleaf裏使用shiro的標籤的bean
     * @return
     */
/*    @Bean
    public ShiroDialect shiroDialect() {
        return new ShiroDialect();
    }*/
 
    @Bean
    ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager) {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        shiroFilterFactoryBean.setLoginUrl("/login");
        shiroFilterFactoryBean.setSuccessUrl("/index");
 
        shiroFilterFactoryBean.setUnauthorizedUrl("/403");
        LinkedHashMap<String, String> filterChainDefinitionMap = new LinkedHashMap<>();
        filterChainDefinitionMap.put("/css/**", "anon");
        filterChainDefinitionMap.put("/js/**", "anon");
        filterChainDefinitionMap.put("/fonts/**", "anon");
        filterChainDefinitionMap.put("/img/**", "anon");
        filterChainDefinitionMap.put("/docs/**", "anon");
        filterChainDefinitionMap.put("/druid/**", "anon");
        filterChainDefinitionMap.put("/upload/**", "anon");
        filterChainDefinitionMap.put("/files/**", "anon");
        filterChainDefinitionMap.put("/logout", "logout");
        filterChainDefinitionMap.put("/", "anon");
        filterChainDefinitionMap.put("/blog", "anon");
        filterChainDefinitionMap.put("/blog/open/**", "anon");
        //filterChainDefinitionMap.put("/**", "authc");
        filterChainDefinitionMap.put("/**", "anon");
 
        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
        return shiroFilterFactoryBean;
    }
 
 
    @Bean
    public SecurityManager securityManager(EhCacheManager ehCacheManager){
        DefaultWebSecurityManager securityManager =  new DefaultWebSecurityManager();
        //設置realm.
        securityManager.setRealm(userRealm());
        // 自定義緩存實現 使用redis
        securityManager.setCacheManager(ehCacheManager);
        securityManager.setSessionManager(sessionManager());
        return securityManager;
    }
    @Bean
    public EhCacheManager ehCacheManager(CacheManager cacheManager) {
        EhCacheManager em = new EhCacheManager();
        //將ehcacheManager轉換成shiro包裝後的ehcacheManager對象
        em.setCacheManager(cacheManager);
        //em.setCacheManagerConfigFile("classpath:ehcache.xml");
        return em;
    }
    /** www.1b23.com
     * shiro session的管理
     */
    @Bean
    public DefaultWebSessionManager sessionManager() {
        DefaultWebSessionManager sessionManager = new DefaultWebSessionManager();
        sessionManager.setGlobalSessionTimeout(tomcatTimeout*1000);
        //設置sessionDao對session查詢,在查詢在線用戶service中用到了
        sessionManager.setSessionDAO(sessionDAO());
        //配置session的監聽
        Collection<SessionListener> listeners = new ArrayList<SessionListener>();
        listeners.add(new BDSessionListener());
        sessionManager.setSessionListeners(listeners);
        //設置在cookie中的sessionId名稱
        sessionManager.setSessionIdCookie(simpleCookie());
        return sessionManager;
    }
 
    @Bean
    public SessionDAO sessionDAO(){
        return new MemorySessionDAO();
    }
 
    @Bean
    public SimpleCookie simpleCookie(){
 
        SimpleCookie simpleCookie = new SimpleCookie();
        simpleCookie.setName("jeesite.session.id");
 
        return simpleCookie;
    }
 
    @Bean
    UserRealm userRealm() {
        UserRealm userRealm = new UserRealm();
        return userRealm;
    }
 
    /**
     *  開啓shiro aop註解支持.
     *  使用代理方式;因此須要開啓代碼支持;
     * @param securityManager
     * @return
     */
    @Bean
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager){
        AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
        authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
        return authorizationAttributeSourceAdvisor;
    }
 
 
 
}
其中:
@Bean
public EhCacheManager ehCacheManager(CacheManager cacheManager) {
    EhCacheManager em = new EhCacheManager();
    //將ehcacheManager轉換成shiro包裝後的ehcacheManager對象
    em.setCacheManager(cacheManager);
    //em.setCacheManagerConfigFile("classpath:ehcache.xml");
    return em;
}
這是配置shiro的緩存管理器org.apache.shiro.cache.ehcach.EhCacheManager,上面的方法的參數是把spring容器中的cacheManager對象注入到EhCacheManager中,這樣就實現了shiro和緩存註解使用同一種緩存方式。
在這裏最大的誤區是下面這樣配置:
    @Bean
    public EhCacheManager ehCacheManager(){
       EhCacheManager cacheManager = new EhCacheManager();
       cacheManager.setCacheManagerConfigFile("classpath:config/ehcache.xml");
       returncacheManager;
    }
必定不要這麼配置,這只是shiro集成了ehcache緩存,根本沒有交給spring容器去管理redis

相關文章
相關標籤/搜索