SpringBoot在注释的层面实现了数据缓存的功能,基于Spring的AOP技术。所有的缓存配置只是在注释层面配置,像声明式事务一样。
春天定义了缓存管理器和缓存器接口统一不同的缓存技术。其中缓存管理器是春天提供的各种缓存技术的抽象接口。而缓存接口包含缓存的各种操作。
<强> CacheManger 强>
针对不同的缓存技术,需要实现不同的缓存管理器,弹簧定义了如下的cacheManger实现。
CacheManger 描述 SimpleCacheManager 使用简单的收集来存储缓存,主要用于测试 ConcurrentMapCacheManager 使用ConcurrentMap作为缓存技术(默认) NoOpCacheManager 测试用 EhCacheCacheManager 使用EhCache作为缓存技术,以前在hibernate的时候经常用 GuavaCacheManager 使用谷歌番石榴的GuavaCache作为缓存技术 HazelcastCacheManager 使用Hazelcast作为缓存技术 JCacheCacheManager 使用JCache标准的实现作为缓存技术,如Apache Commons JCS RedisCacheManager 使用复述,作为缓存技术
常规的SpringBoot已经为我们自动配置了EhCache,收集,番石榴,ConcurrentMap等缓存,默认使用ConcurrentMapCacheManager.SpringBoot的application.properties配置文件,使用spring.cache前缀的属性进行配置。
<强>应用配置强>
spring.cache.type=#缓存的技术类型 spring.cache.cache-names=应用程序启动创建缓存的名称 spring.cache.ehcache.config=ehcache的配置文件位置 spring.cache.infinispan.config=infinispan的配置文件位置 spring.cache.jcache.config=jcache配置文件位置 spring.cache.jcache.provider=当多个jcache实现类时,指定选择jcache的实现类
<强>入口类配置强>
加入注解@EnableCaching
<强>缓存注解强>
注解 描述 @Cacheable 在调用方法之前,首先应该在缓存中查找方法的返回值,如果这个值能够找的到,就会返回缓存的值,否则,这个方法就会被调用,返回值会放到缓存之中。 @CachePut 将方法的返回值放到缓存中。在方法的调用前并不会检查缓存,方法始终都会被调用。 @CacheEvict 在缓存中清除一个或多个条目。 @Caching 分组的注解,能够同时应用多个其他的缓存注解。
<强>手动使用EhCache 强>
在实际开发过程中,存在不使用注解,需要自己添加缓存的情况下,面就以Ehcache为例,简单写一下配置过程。
<强> 1。添加依赖强>
引入springboot-cache和ehcache。需要注意,ehcache不需要配置版本,SpringBoot的根pom已经集成了。
& lt; !——缓存——比; & lt; dependency> & lt; groupId> org.springframework.boot & lt; artifactId> spring-boot-starter-cache & lt;/dependency> & lt; !——ehcache祝辞 & lt; dependency> & lt; groupId> net.sf.ehcache & lt; artifactId> ehcache & lt;/dependency>
2。入口类配置
加入注解@EnableCaching
@SpringBootApplication @EnableCaching 公开课DemoApplication { }
3。EhCache配置
主要在src \ \资源目录下,添加ehcache.xml文件,内容见文末。
4。应用程序。应用配置
#配置ehcache缓存 spring.cache.type=ehcache #指定ehcache配置文件路径 spring.cache.ehcache.config=类路径:/ehcache.xml >之前5。使用缓存
注入SpringBoot自动配置的bean, org.springframework.cache。缓存管理器。
一个简单的测试类:
包com.bbf.frame.test; 进口com.bbf.frame.Application; 进口org.apache.commons.lang3.StringUtils; 进口org.junit.Test; 进口org.junit.runner.RunWith; 进口org.springframework.boot.test.context.SpringBootTest; 进口org.springframework.cache.Cache; 进口org.springframework.cache.CacheManager; 进口org.springframework.test.context.junit4.SpringJUnit4ClassRunner; 进口org.springframework.test.context.web.WebAppConfiguration; 进口javax.annotation.Resource; @RunWith (SpringJUnit4ClassRunner.class) @WebAppConfiguration @SpringBootTest(类=应用程序。类,webEnvironment=SpringBootTest.WebEnvironment.MOCK) 公开课TestCache { @ 私人CacheManager缓存管理器; @Test 公共空间声望(){//显示所有的缓存空间 System.out.println (StringUtils.join (cacheManager.getCacheNames (), ", ")); 缓存缓存=cacheManager.getCache (“userCache”); 缓存。把(“关键”、“123”); System.out.println(“缓存成功”); 字符串res=缓存。(“关键”,String.class); System.out.println (res); } }SpringBoot手动使用EhCache的方法示例