spring+ehcache+註解的使用java
爲了提升系統的運行效率,引入緩存機制,減小數據庫訪問和磁盤IO。下面說明一下ehcache和spring整合配置。spring
總共須要四步,引入包,添加ehcache.xml文件,在spring的配置文件applicationContext.xml中添加ehcache的配置,在service層裏的方法上添加ehcache註解。數據庫
1.須要的包緩存
ehcache-core-2.1.0.jarapp
ehcache-spring-annotations-1.1.2.jarspa
2.ehcache.xml文件xml
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchemainstance" get
xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd">
<diskStore path="java.io.tmpdir/ehcache"/>
<!-- 默認緩存 -->
<defaultCache
maxElementsInMemory="1000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
overflowToDisk="false"/>
<!-- 菜單緩存 -->
<cache name="userCache"
maxElementsInMemory="1000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
overflowToDisk="false"
memoryStoreEvictionPolicy="LRU"/>
</ehcache>
io
3.applicationContext.xml文件class
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:cache="http://www.springframework.org/schema/cache"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/cache
http://www.springframework.org/schema/cache/spring-cache-3.2.xsd">
<cache:annotation-driven cache-manager="cacheManager"/>
<bean id="cacheManagerFactory" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
<property name="configLocation" value="classpath:/ehcache.xml" />
</bean>
<bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager">
<property name="cacheManager" ref="cacheManagerFactory"/>
</bean>
</beans>
4.使用 在service層的方法上加註解
(1)添加緩存
@Cacheable(value="userCache")
public List<user> findUserList()
{
……
}
(2)清除緩存
@CacheEvict(value="userCache")
public boolean delUser(User user) {
……
}
這樣既可實現緩存。