spring源码分析之cache demo
2016-07-22 16:26
323 查看
spring提供了对echache、guava、jcache的支持,先看一个echache的示例:
其中 echache.xml文件如下:
缓存的使用:
参考文献:
【1】http://www.mkyong.com/spring/spring-caching-and-ehcache-example/
import org.springframework.cache.CacheManager; import org.springframework.cache.annotation.EnableCaching; import org.springframework.cache.ehcache.EhCacheCacheManager; import org.springframework.cache.ehcache.EhCacheManagerFactoryBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.core.io.ClassPathResource; @Configuration @EnableCaching @ComponentScan({ "com.mkyong.*" }) public class AppConfig { @Bean public CacheManager cacheManager() { return new EhCacheCacheManager(ehCacheCacheManager().getObject()); } @Bean public EhCacheManagerFactoryBean ehCacheCacheManager() { EhCacheManagerFactoryBean cmfb = new EhCacheManagerFactoryBean(); cmfb.setConfigLocation(new ClassPathResource("ehcache.xml")); cmfb.setShared(true); return cmfb; } /*@Bean public CacheManager defaultCacheManager() { return new ConcurrentMapCacheManager("books"); }*/ }
其中 echache.xml文件如下:
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="ehcache.xsd" updateCheck="true" monitoring="autodetect" dynamicConfig="true"> <!-- <diskStore path="java.io.tmpdir" /> --> <diskStore path="c:\\cache" /> <cache name="movieFindCache" maxEntriesLocalHeap="10000" maxEntriesLocalDisk="1000" eternal="false" diskSpoolBufferSizeMB="20" timeToIdleSeconds="300" timeToLiveSeconds="600" memoryStoreEvictionPolicy="LFU" transactionalMode="off"> <persistence strategy="localTempSwap" /> </cache> </ehcache>
缓存的使用:
@Repository("movieDao") public class MovieDaoImpl implements MovieDao{ @Cacheable(value="movieFindCache", key="#name") public Movie findByDirector(String name) { slowQuery(2000L); System.out.println("findByDirector is running..."); return new Movie(1,"Forrest Gump","Robert Zemeckis"); } private void slowQuery(long seconds){ try { Thread.sleep(seconds); } catch (InterruptedException e) { throw new IllegalStateException(e); } } }
参考文献:
【1】http://www.mkyong.com/spring/spring-caching-and-ehcache-example/
相关文章推荐
- 解决angular+spring boot的跨域问题
- Spring autowire自动装配
- 线程基础介绍一
- 《Java源码分析》:HashSet
- 不使用构造方法创建Java对象 Objenesis
- Caused by: java.lang.IncompatibleClassChangeError: class org.springframework.scheduling.quartz.CronTriggerBean has interface org.quartz.CronTrigger as super class
- JAVA反射详解
- JAVA利用POI实现excel的导入导出
- spring boot 加载本地静态资源文件路径配置
- Java垃圾回收机制
- Eclipse安装Maven插件
- 理解RxJava:(一)基础知识
- MyEclipse自动添加头时间、作者、文件注释等。
- JAVA CAS单点登录(SSO)
- JAVA CAS单点登录(SSO)
- java lock 的使用
- Thinking in Java 第19章 枚举类型
- @Resource、@Autowired、@Qualifier的注解注入及区别
- Java基本语法-----java二维数组
- Java基本语法-----java二维数组