Shiro性能優化--EhCache

* evict : 驅逐,趕出

ps : 使用shiro進行權限管理後,每次都須要調用realm查詢角色和權限,每次都須要查數據庫,性能不是很好java

pps : 是否能夠將數據庫中的數據放到緩存中,減小數據庫交互,提升性能?web

一:技術選型

爲何使用ehcache而不使用redis緩存?

  1. Shiro 默認對 ehcache 的支持

  1. 在後臺管理系統中 ehcache 使用很是廣泛

二:spring整合ehcache

(一)maven依賴

<dependency>
	<groupId>net.sf.ehcache</groupId>
	<artifactId>ehcache-core</artifactId>
	<version>2.6.11</version>
</dependency>
<dependency>
	<groupId>org.springframework</groupId>
	<artifactId>spring-context-support</artifactId>
	<version>4.2.8.RELEASE</version>
</dependency>

(二)導入ehcache.xml配置文件

  • 解壓ehcache-core.jar包 ,將ehcache-failsafe.xml複製src/main/resources更名ehcache.xml

  • 默認緩存區
<defaultCache
	maxElementsInMemory="10000"
	eternal="false"
	timeToIdleSeconds="120"
	timeToLiveSeconds="120"
	maxElementsOnDisk="10000000"
	diskExpiryThreadIntervalSeconds="120"
	memoryStoreEvictionPolicy="LRU">
	<persistence strategy="localTempSwap"/>
</defaultCache>
  • 能夠自定義緩存區(不想改的話照着默認的寫)
<cache name="myCache"
	maxElementsInMemory="10000"
	eternal="false"
	timeToIdleSeconds="120"
	timeToLiveSeconds="120"
	maxElementsOnDisk="10000000"
	diskExpiryThreadIntervalSeconds="120"
	memoryStoreEvictionPolicy="LRU">
	<persistence strategy="localTempSwap"/>
</cache>

(三)將EhCache交給Spring管理

<!-- spring整合ehcache -->
<bean id="ehCacheManager"
	class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
	<property name="configLocation" value="classpath:ehcache.xml"/>
</bean>

三:shiro整合ehcache

(一)配置shiro的緩存管理器,封裝ehcache

<!-- shiro封裝ehCacheManager -->
<bean id="shiroCacheManager" 
	class="org.apache.shiro.cache.ehcache.EhCacheManager" >
	<property name="cacheManager" ref="ehCacheManager"/>
</bean>

(二)將shiro的緩存管理器,注入到安全管理器中

<!-- 配置subject的後臺推手securityManager -->
<bean id="securityManager" 
	class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
	<property name="realm" ref="myRealm"/>
	<property name="cacheManager" ref="shiroCacheManager"/>
</bean>

(三)爲認證受權數據指定緩存區

<bean id="myRealm" class="club.info.bos.realm.MyRealm">
	<property name="authorizationCacheName" value="myCache"/>
</bean>
  • 注意 : 須要緩存的對象要實現serializable接口

四:緩存聲明

  • spring提供一套整合緩存器的註解
  • 開啓註解緩存
<bean id="springCacheManager" 
	class="org.springframework.cache.ehcache.EhCacheCacheManager">
	<property name="cacheManager" ref="ehCacheManager"/>
</bean>
	
<cache:annotation-driven cache-manager="springCacheManager"/>

(一)@CacheEvict

  • 清除緩存,一般數據庫數據發生變化後,清除緩存,如增,刪改
@Override
@CacheEvict(value="myCache",allEntries=true)
public void save(User user) {
	userDao.save(user);
}

(二)@Cacheable("緩存區名稱")

  • 能緩存的,查詢後緩存

1.緩存無參方法的返回值

@Override
@Cacheable("myCache")
public List<User> findAll() {
	return userDao.findAll();
}

2.緩存有參方法的返回值

  • 針對數據在不一樣條件下進行不一樣緩存,咱們能夠指定緩存的key,支持對象嵌套,支持spel表達式
@Override
@Cacheable(value="myCache",key="#pageable.pageNumber+'_'+#pageable.pageSize")
public List<User> findPageData(Pageable pageable) {
	return userDao.findAll(pageable);
}
相關文章
相關標籤/搜索