【问题标题】:apply ehCache on entities from jar对来自 jar 的实体应用 ehCache
【发布时间】:2021-09-06 22:34:26
【问题描述】:

我正在为应用程序使用 Spring Boot 2.0 版。在这里,我们使用了一个包含大量实体的第三方 jar 文件。为了提高应用程序的性能,我们确实需要对这些 jar 包含的实体进行二级缓存。由于我们在应用程序中使用了 Hibernate,因此我们首选 EhCache 提供程序来实现二级缓存。

大多数网站都提供带有注释@Cacheable 的示例,这在我们的应用程序中不可用,因为我们使用的 jar 文件实体仅包含不可编辑的类文件。因此,如果有人提供使用 xml 缓存这些 jar 文件实体的代码以及如何在 ehCacheManager 中配置这些实体,那将非常有帮助。

版本

  • 休眠 v5.x +
  • ehCache v2.x +
  • Spring Boot v2.x +

【问题讨论】:

    标签: java spring-boot hibernate ehcache


    【解决方案1】:

    ehcache 可以使用 XML 配置,这里是一个小例子

    src/main/resources内创建一个名为ehcache.xml的文件

    <?xml version="1.0" encoding="UTF-8"?>
    <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="ehcache.xsd" updateCheck="true"
        monitoring="autodetect" dynamicConfig="true">
        <diskStore path="java.io.tmpdir/ehcache" />
        <defaultCache maxElementsInMemory="1000" eternal="false"
            timeToIdleSeconds="3" timeToLiveSeconds="120" overflowToDisk="true" />
        <cache
            name="your.entity.in.jar.Entity"
            maxElementsInMemory="100" eternal="false" timeToIdleSeconds="3"
            timeToLiveSeconds="120" overflowToDisk="false" />
    </ehcache>
    

    访问 ehcache 网站了解更多详情

    https://www.ehcache.org/documentation/2.8/configuration/configuration.html

    【讨论】:

    • 我按照你的建议做了同样的事情......但是,结果没有被缓存。每次,数据库都会发生。所以,请提供更多帮助。
    【解决方案2】:

    如果您无法使用@Cacheable 注释实体,您可以将SharedCacheMode 设置为ALL

    answer 解释了如何设置二级缓存,在您的情况下,您应该将模式从ENABLE_SELECTIVE 更改为ALL。另一个answer 也应该有帮助。

    【讨论】:

    • 完成上述从 ENABLE_SELECTIVE 到 ALL 的更改。仍然没有缓存。
    • 你必须分享更多关于你正在做什么的信息,尤其是应用程序启动时的配置文件和日志
    • 下面是persistence.xml:
    【解决方案3】:

    最后,我通过启用以下方式使其工作。

    Persistence.xml:

    <persistence>
    //few lines
    <shared-cache-mode>ALL</shared-cache-mode>
    </persistence>
    

    eh-cache.xml:

    <defaultCache name="default" maxElementsInMemory="500"
     eternal="false" timeToIdleSeconds="6000" timeToLiveSeconds="12000"
     overflowToDisk="false" diskPersistent="false"
     memoryStoreEvictionPolicy="LRU" />
    

    在启用的配置文件中,ehcache 区域工厂的二级缓存为 true。

    缓存仅适用于没有连接的单表查询,没有内部查询。有没有人帮我让它也适用于连接查询和内部查询。?

    注意事项

    1. 由于我们处理类文件,因此无法进行注释

    @Cacheable 或 @Cache 在实体类的集合属性之上是不可能的,因为我们正在处理类文件(使用 jar 中的实体类)。 例如:

    @Setter
    @Getter
    @NoArgsConstructor
    @AllArgsConstructor
    @Entity
    @Table(name = "TABLE_NAME" ,schema ="SCHEMA_NAME")
    public class SampleEntity {
        @Cacheable
        @org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE) ***//not possible here since we deals with class files***
        @OneToMany
        private Collection<Bar> bars; 
    } 
    
    1. jpa 注解已经只用在实体类文件中,只有缓存缺失,我们需要在不影响类文件的情况下进行配置。

    【讨论】:

    • 没有人会在你的回答中寻找你的新问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-17
    • 1970-01-01
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多