作者:谭朝红
<强> 强>
本次内容主要介绍基于Ehcache 3.0来快速实现弹簧引导应用程序的数据缓存功能,在春天的引导应用程序中,我们可以通过春天缓存来快速搞定数据缓存。
1。创建一个弹簧引导工程
你所创建的弹簧引导应用程序的maven依赖文件至少应该是下面的样子:
& lt; ?xml version=" 1.0 " encoding=" utf - 8 " ?比; & lt;项目xmlns=" http://maven.apache.org/POM/4.0.0 " xmlns: xsi=" http://www.w3.org/2001/XMLSchema-instance " xsi: schemaLocation=" http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd”比; & lt; modelVersion> 4.0.0 & lt; parent> & lt; groupId> org.springframework.boot & lt; artifactId> spring-boot-starter-parent & lt; version> 2.1.3.RELEASE & lt; relativePath/比;& lt; !——从库中查找父——比; & lt;/parent> & lt; groupId> com.ramostear & lt; artifactId> cache & lt; version> 0.0.1-SNAPSHOT & lt; name> cache 春天Boot< & lt; description>演示项目;/description> & lt; properties> & lt; java.version> 1.8 & lt;/java.version> & lt;/properties> & lt; dependencies> & lt; dependency> & lt; groupId> org.springframework.boot & lt; artifactId> spring-boot-starter-cache & lt;/dependency> & lt; dependency> & lt; groupId> org.springframework.boot & lt; artifactId> spring-boot-starter-web & lt;/dependency> & lt; dependency> & lt; groupId> org.ehcache & lt; artifactId> ehcache & lt;/dependency> & lt; dependency> & lt; groupId> javax.cache & lt; artifactId> cache-api & lt;/dependency> & lt; dependency> & lt; groupId> org.springframework.boot & lt; artifactId> spring-boot-starter-test & lt; scope> test & lt;/dependency> & lt; dependency> & lt; groupId> org.projectlombok & lt; artifactId> lombok & lt;/dependency> & lt;/dependencies> & lt; build> & lt; plugins> & lt; plugin> & lt; groupId> org.springframework.boot & lt; artifactId> spring-boot-maven-plugin & lt;/plugin> & lt;/plugins> & lt;/build> & lt;/project>
- <李>
李> <李>
李> <李>
李>
2。配置Ehcache缓存
现在,需要告诉弹簧引导去那里找缓存配置文件,这需要在春天引导配置文件中进行设置:
spring.cache.jcache.config=类路径:Ehcache。xml
然后使用@EnableCaching注解开启弹簧引导应用程序缓存功能,你可以在应用主类中进行操作:
包com.ramostear.cache; 进口org.springframework.boot.SpringApplication; 进口org.springframework.boot.autoconfigure.SpringBootApplication; 进口org.springframework.cache.annotation.EnableCaching; @SpringBootApplication @EnableCaching 公开课CacheApplication { 公共静态void main (String [] args) { SpringApplication.run (CacheApplication.class, args); } }
接下来,需要创建一个ehcache的配置文件,该文件放置在类路径下,如资源目录下:
& lt;配置xmlns: xsi=" http://www.w3.org/2001/XMLSchema-instance " xmlns=" http://www.ehcache.org/v3 " xmlns: jsr107=" http://www.ehcache.org/v3/jsr107 " xsi: schemaLocation=" http://www.ehcache.org/v3 http://www.ehcache.org/schema/ehcache-core-3.0.xsd http://www.ehcache.org/v3/jsr107 http://www.ehcache.org/schema/ehcache - 107 - ext - 3.0.xsd”比; & lt; service> & lt; jsr107:默认启用统计数据=" true "/比; & lt;/service>=& lt;缓存别名“人”在 & lt; key-type> java.lang.Long & lt; value-type> com.ramostear.cache.entity.Person & lt; expiry> & lt; ttl单位="分钟"祝辞1 & lt;/ttl> & lt;/expiry> & lt; listeners> & lt; listener> & lt; class> com.ramostear.cache.config.PersonCacheEventLogger & lt; event-firing-mode> ASYNCHRONOUS3步轻松搞定春引导缓存