spring配置文件
<cache:annotation-driven cache-manager="cacheManager" /> <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager"> <property name="cacheManager" ref="ehcache"></property> </bean> <bean id="ehcache" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"> <property name="configLocation" value="classpath:ehcache.xml"></property> </bean>
ehcache文件
<?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"> <diskStore path="java.io.tmpdir" /> <defaultCache eternal="false" maxElementsInMemory="1000" overflowToDisk="false" diskPersistent="false" timeToIdleSeconds="0" timeToLiveSeconds="600" memoryStoreEvictionPolicy="LRU" /> <cache name="departCache" eternal="false" maxElementsInMemory="100" overflowToDisk="false" diskPersistent="false" timeToIdleSeconds="0" timeToLiveSeconds="300" memoryStoreEvictionPolicy="LRU" /> </ehcache>
实现类
import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Service; @Service public class CacheServiceImpl implements CacheService{ @Cacheable(value="departCache",key="#i") public String findUser(int i) { StringBuffer sb=new StringBuffer(); int j=0; for(;j<i;j++){ sb.append("hello"+i); } return sb.toString(); } }
测试类
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("/application.xml") public class TestCache { @Resource CacheServiceImpl cacheServiceImpl; @Test public void testSend() { System.out.println(System.currentTimeMillis()); cacheServiceImpl.findUser(1000); System.out.println(System.currentTimeMillis()); System.out.println(System.currentTimeMillis()); cacheServiceImpl.findUser(1000); System.out.println(System.currentTimeMillis()); } }
时间: 2024-10-16 23:26:35