本文共 1352 字,大约阅读时间需要 4 分钟。
本地缓存其实项目中用得还比较多,常用的ehcache,现整合spring-boot搭建一个demo方便以后查阅。
下面2个依赖是spring-boot整合ehcache必须的依赖
org.springframework.boot spring-boot-starter-cache ${spring-boot.version} net.sf.ehcache ehcache 2.10.3
如果启用spring-boot单元测试,还需要加入下面的依赖。
org.springframework.boot spring-boot-starter-test ${spring-boot.version} test
application.properties中指明ehcache配置文件
spring.cache.jcache.config=ehcache.xml
ehcache.xml配置ehcache缓存,具体配置项的意义请参考。
在spring-boot启动类加上@EnableCaching
注解,表明该项目启用缓存。
@EnableCaching@EnableScheduling@SpringBootApplicationpublic class ItcljApplication { public static void main(String[] args) { new SpringApplicationBuilder().sources(ItcljApplication.class) .profiles("app").run(args); }}
使用缓存其实很简单,只需要在缓存的方法上加上@Cacheable
注解即可,@CacheEvict
、@CachePut
等缓存相关注解另行查询其他资料。
@Component@CacheConfig(cacheNames = "countries")public class CountryRepository { @Cacheable(key = "'country'+#code") public Country findByCode(String code) { System.out.println("---> Loading country with code '" + code + "'"); return new Country(code); }}
原文地址:
项目地址:转载地址:http://suvmb.baihongyu.com/