Java学习笔记Spring Boot程序员

spring hibernate cache

2016-06-21  本文已影响332人  搁浅的双鱼

what

其实你就可以想象成一个 Map ,通过 key 在缓存里面找 value 。类似于session这种东西

来一个比较官方的解释

缓存是数据库数据临时容器,它包含了库表数据的临时拷贝,位于数据库与数据访问层之间。ORM进行数据读取时,会根据其缓存管理策略,首先在内存中查询,如果在内存中发现所需数据(缓存命中),则直接以此数据错位查询结果加以利用,从而避免了数据库调用的性能开销。

why

EhCache是Hibernate的二级缓存技术之一,可以把查询出来的数据存储在内存或者磁盘,节省下次同样查询语句再次查询数据库,大幅减轻数据库压力;

how

我是在spring boot框架下的配置

在application.properties配置中打开二级缓存
spring.jpa.properties.hibernate.cache.region.factory_class = org.hibernate.cache.ehcache.EhCacheRegionFactory
spring.jpa.properties.net.sf.ehcache.configurationResourceName = config/cache/ehcache.hibernate.xml
spring.jpa.properties.javax.persistence.sharedCache.mode = ENABLE_SELECTIVE
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
在实体类中添加缓存注解
@Des("所属组织")
@ManyToOne
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
private Org org;
在config下面的cache中配置ehcache.hibernate.xml
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:noNamespaceSchemaLocation="ehcache.xsd" name="hibernateServicecache" updateCheck="false"
    monitoring="autodetect" dynamicConfig="true">
    <diskStore path="java.io.tmpdir/ehcache" />
    <defaultCache maxElementsInMemory="10000" eternal="false"
        timeToIdleSeconds="120" timeToLiveSeconds="120" overflowToDisk="true"
        maxElementsOnDisk="10000000" diskPersistent="false"
        diskExpiryThreadIntervalSeconds="120" memoryStoreEvictionPolicy="LRU" >
    </defaultCache>
</ehcache>
缓存策略详解

如果有啥问题,大家一起探讨探讨!

参考资料1

参考资料2

参考资料3

上一篇 下一篇

猜你喜欢

热点阅读