本文将介绍如何在spring boot中集成ehcache作为hibernate的二级缓存。各个框架版本如下
项目依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId></dependency><dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-cache</artifactId></dependency><dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-ehcache</artifactId> <exclusions> <exclusion> <groupId>net.sf.ehcache</groupId> <artifactId>ehcache-core</artifactId> </exclusion> </exclusions></dependency><dependency> <groupId>net.sf.ehcache</groupId> <artifactId>ehcache</artifactId> <version>2.10.3</version></dependency>Ehcache简介
ehcache是一个纯Java的缓存框架,既可以当做一个通用缓存使用,也可以作为将其作为hibernate的二级缓存使用。缓存数据可选择如下三种存储方案
hibernate二级缓存配置
hibernate的二级缓存支持entity和query层面的缓存,org.hibernate.cache.spi.RegionFactory各类可插拔的缓存提供商与hibernate的集成。
# 打开hibernate统计信息spring.jpa.properties.hibernate.generate_statistics=true# 打开二级缓存spring.jpa.properties.hibernate.cache.use_second_level_cache=true# 打开查询缓存spring.jpa.properties.hibernate.cache.use_query_cache=true# 指定缓存providerspring.jpa.properties.hibernate.cache.region.factory_class=org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory# 配置shared-cache-modespring.jpa.properties.javax.persistence.sharedCache.mode=ENABLE_SELECTIVE关于hibernate缓存相关的所有配置可参考hibernate5.0官方文档#缓存
ehcache配置文件
ehcache 2.x配置文件样板参考官方网站提供的ehcache.xml。本例中使用的配置文件如下所示
<?xml version="1.0" encoding="UTF-8"?><ehcache xmlns:xsi="http://.yangyi;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.cache.annotation.EnableCaching;@SpringBootApplication@EnableCachingpublic class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); }}完整代码
完整代码示例见github
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。