java - 如何通过注释正确配置 2 级 hibernate 实体缓存

标签 java hibernate spring-data-jpa spring-cache ehcache-2

我想在 Spring Boot 微服务中配置二级 hibernate 缓存。 而且我根本不想使用 xml。 接下来是我的例子。

用户实体.java

@Entity
@Table(name = "users")
@Cacheable
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region = "users")
public class UserEntity {

    @Id
    private long id;

    @Column
    private String name;

    public UserEntity(long id, String name) {
        this.id = id;
        this.name = name;
    }

   // ... geters&setters
}

缓存配置文件

import net.sf.ehcache.config.CacheConfiguration;
import net.sf.ehcache.store.MemoryStoreEvictionPolicy;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableCaching
public class CacheConfig {

    @Bean
    public org.springframework.cache.CacheManager cacheManager() {
        return new EhCacheCacheManager(ehCacheManager());
    }

    private net.sf.ehcache.CacheManager ehCacheManager() {

        CacheConfiguration usersCacheConfiguration = new CacheConfiguration();
        usersCacheConfiguration.setName("users");
        usersCacheConfiguration.eternal(false);
        usersCacheConfiguration.setMaxEntriesInCache(1000);
        usersCacheConfiguration.setMaxEntriesLocalDisk(0);
        usersCacheConfiguration.memoryStoreEvictionPolicy(MemoryStoreEvictionPolicy.LRU);

        net.sf.ehcache.config.Configuration config = new net.sf.ehcache.config.Configuration();
        config.addCache(usersCacheConfiguration);

        return net.sf.ehcache.CacheManager.create(config);
    }
}

应用程序.java

@SpringBootApplication
public class App {

    public static void main(String[] args) {
        new SpringApplicationBuilder(App.class)
                .sources(CacheConfig.class)
                .run(args);
    }

}

应用程序属性

spring:
  datasource:
    url: jdbc:postgresql://localhost:5432/test
    username: postgres
    password: postgres
    type: com.zaxxer.hikari.HikariDataSource
    driverClassName: org.postgresql.Driver
  jpa.hibernate.ddl-auto: update
  jpa.open-in-view: false
  jpa.properties.javax.persistence.sharedCache.mode: ALL
  jpa.properties.hibernate:
    dialect: org.hibernate.dialect.PostgreSQL9Dialect
    jdbc.batch_size: 100
    temp.use_jdbc_metadata_defaults: false
    order_inserts: true
    cache:
      region.factory_class: org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory
      #region.factory_class: org.hibernate.cache.ehcache.EhCacheRegionFactory
      #region_prefix: ""
      use_second_level_cache: true
      cache.use_query_cache: true
      provider_class: org.hibernate.cache.EhCacheProvider

构建.gradle

group 'com.hibernate.cache'
version '1.0-SNAPSHOT'

apply plugin: 'java'

sourceCompatibility = 1.8

repositories {
    mavenCentral()
}

dependencies {
    compile group: 'org.springframework.boot', name: 'spring-boot-starter-data-jpa', version: '2.0.0.RELEASE'
    compile group: 'org.springframework', name: 'spring-context-support', version: '5.0.4.RELEASE'
    compile group: 'org.hibernate', name: 'hibernate-ehcache', version: '5.2.14.Final'
    compile group: 'org.postgresql', name: 'postgresql', version: '42.1.4'
}

当我运行该程序时,我看到一些警告,表明未应用实体缓存配置:

2018-03-04 23:29:48.723  WARN 8516 --- [           main] n.s.ehcache.config.ConfigurationFactory  : No configuration found. Configuring ehcache from ehcache-failsafe.xml  found in the classpath: jar:file:/home/vitaly/.gradle/caches/modules-2/files-2.1/net.sf.ehcache/ehcache/2.10.3/cf74f9a4a049f181833b147a1d9aa62159c9d01d/ehcache-2.10.3.jar!/ehcache-failsafe.xml
2018-03-04 23:29:48.834  WARN 8516 --- [           main] o.h.c.e.AbstractEhcacheRegionFactory     : HHH020003: Could not find a specific ehcache configuration for cache named [users]; using defaults.

有人知道这里出了什么问题吗?

最佳答案

第一个警告:

2018-03-04 23:29:48.723  WARN 8516 --- [           main] n.s.ehcache.config.ConfigurationFactory  : No configuration found. Configuring ehcache from ehcache-failsafe.xml  found in the classpath: jar:file:/home/vitaly/.gradle/caches/modules-2/files-2.1/net.sf.ehcache/ehcache/2.10.3/cf74f9a4a049f181833b147a1d9aa62159c9d01d/ehcache-2.10.3.jar!/ehcache-failsafe.xml

表示未找到 ehcache.xml 配置,因此使用默认值 ehcache-failsafe.xml。

第二个警告:

2018-03-04 23:29:48.834  WARN 8516 --- [           main] o.h.c.e.AbstractEhcacheRegionFactory     : HHH020003: Could not find a specific ehcache configuration for cache named [users]; using defaults.

表示在缓存中没有找到“用户”区域的配置。当然,它没有在 ehcache-failsafe.xml 中定义,而且它看起来不像 CacheConfig 中的设置正在被拾取 - 至少 CacheManager 没有由 Hibernate 使用。

应该可以通过将 ehcache.xml 添加到类路径(在 src/main/resources 中)来解决这两个问题,例如:

<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="http://www.ehcache.org/ehcache.xsd"
         updateCheck="true"
         monitoring="autodetect"
         dynamicConfig="true">

    <cache name="users"
           maxEntriesLocalHeap="500"
           eternal="false"
           timeToIdleSeconds="300"
           timeToLiveSeconds="600"
           diskExpiryThreadIntervalSeconds="1"
           copyOnRead="true"
           copyOnWrite="true">
        <copyStrategy class="net.sf.ehcache.store.compound.ReadWriteSerializationCopyStrategy" />
    </cache>

</ehcache>

(有关更多选项,请参阅 this ehcache.xml sample)

并将以下内容添加到 application.yml 中:

spring:
  cache:
    ehcache:
      config: classpath:ehcache.xml

关于java - 如何通过注释正确配置 2 级 hibernate 实体缓存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49100209/

相关文章:

java - 如何将 LocalContainerEntityManagerFactoryBean 设置为 JpaTransactionManager?

java - 继承、动态绑定(bind)、父类(super class)中的构造函数。 java

java - 如何覆盖继承类上的 hibernate JPA 过滤器?

java - 删除多对多条目,同时将两个对象都保留在数据库中

spring - org.hibernate.TransientObjectException : The given object has a null identifier

spring - 为具有复合 ID 的实体自定义 HATEOAS 链接生成

java - NXP NFC NDEF 标签内存大小问题

java - 变量的不同步读/写可能会导致数据竞争?

java - 在 Java 中使用 CUP 的 Parser.cup

hibernate - 流式查询结果提前关闭 - Spring Data JPA 和 Hibernate