1. 程式人生 > >Mybatis + Shiro 使用ehcache做二級快取

Mybatis + Shiro 使用ehcache做二級快取

1、mybatis的ehcache依賴:

<!-- mybatis + ehcache  start-->
<dependency>
  	<groupId>org.mybatis</groupId>
	<artifactId>mybatis-ehcache</artifactId>
	<version>1.0.0</version>
</dependency>

<dependency>
  	<groupId>org.ehcache</groupId>
  	<artifactId>ehcache</artifactId>
  	<version>3.0.1</version>
</dependency>
<!-- mybatis + ehcache  end-->

2、shiro的ehcache依賴:

<!-- shiro start-->
<dependency>
	<groupId>org.apache.shiro</groupId>
	<artifactId>shiro-spring</artifactId>
	<version>1.2.3</version>
</dependency>

<dependency>
	<groupId>net.sf.ehcache</groupId>
	<artifactId>ehcache-core</artifactId>
	<version>2.6.9</version>
</dependency>

<dependency>
	<groupId>org.apache.shiro</groupId>
	<artifactId>shiro-ehcache</artifactId>
	<version>1.2.3</version>
</dependency>

<dependency>
	<groupId>net.sf.ehcache</groupId>
	<artifactId>ehcache-web</artifactId>
	<version>2.0.4</version>
</dependency>
<!-- shiro end -->

3、因為兩者都有ehcache,所以需要共享ehcache,mybatis配置檔案中,加入:

<!-- MyBatis使用ehcache快取 start -->  
<bean id="ehCacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
    <property name="configLocation" value="classpath:ehcache.xml"/>
     <!-- 和shiro分享快取  --> 
    <property name="shared" value="true"></property> 
</bean> 
<!-- end MyBatis使用ehcache快取 -->  

<!-- shiro快取管理器 使用Ehcache實現 -->  
<bean id="shiroCacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">  
    <property name="cacheManager" ref="ehCacheManager" />  
</bean>     

4、作用

1、使mybatis和shiro共享ehcache
2、使同一個查詢,只查詢一次,第一次查詢後,放到ehcache裡面,後面直接從快取取