β

Spring+Ehcache使用

Jeremy Peng's Blog 290 阅读

配置Maven依赖:

<!-- ehcache -->
		<dependency>
			<groupId>net.sf.ehcache</groupId>
			<artifactId>ehcache</artifactId>
			<version>2.9.1</version>
		</dependency>
		<!-- ehcache -->

在Spring配置文件中配置:

<!-- cache -->
    <cache:annotation-driven proxy-target-class="true" />
    <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager"
        p:cache-manager-ref="ehcache" />
    <bean id="ehcache"
        class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"
        p:config-location="classpath:ehcache.xml" p:shared="true" />
    <!-- end cache -->

添加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">
	<!--
     Please see http://ehcache.sourceforge.net/documentation/configuration.html for
     detailed information on how to configure caches in this file
	-->
	<defaultCache maxElementsInMemory="1000" eternal="false" timeToIdleSeconds="120" timeToLiveSeconds="120" overflowToDisk="false" />

	<cache name="userAccountCache" maxElementsInMemory="1000" eternal="true" overflowToDisk="false" />
</ehcache>

在需要缓存的地方:

@Cacheable(value = "userAccountCache", key = "#username")
	public UserAccount getUserAccount(String username) {
		UserAccount userAccount = userDao.getUserAccount(username);
		return userAccount;
	}

在需要踢出缓存的地方:

@CacheEvict(value = "userAccountCache", key = "#username")
	public void updateUserAccount(String username) {
		userDao.updateUserAccount(username);
	}
作者:Jeremy Peng's Blog
劳心者治人,劳力者治于人
原文地址:Spring+Ehcache使用, 感谢原作者分享。

发表评论