Hibernate 的應(yīng)用6 —— 二級(jí)緩存

Hibernate 二級(jí)緩存

Hibernate 二級(jí)緩存 總結(jié)整理

  • 可以在進(jìn)程或集群的級(jí)別上為事務(wù)之間可重用的數(shù)據(jù)提供二級(jí)緩存
  • SessionFactory 的二級(jí)緩存是全局性的,所有 Session 都共享這個(gè)二級(jí)緩存。默認(rèn)關(guān)閉
  • 查詢時(shí)使用緩存的實(shí)現(xiàn)過程為:首先查詢一級(jí)緩存中是否具有需要的數(shù)據(jù),如果沒有,查詢二級(jí)緩存,如果二級(jí)緩存中也沒有,此時(shí)再執(zhí)行查詢數(shù)據(jù)庫(kù)的工作
  • Hibernate 并不為二級(jí)緩存提供實(shí)現(xiàn)方法,而是為 Hibernate 第三方緩存插件整合了接口
  • 可以為每一個(gè) 持久化類 或每一個(gè) 集合 進(jìn)行二級(jí)緩存的配置
  • 刪除、更新、增加數(shù)據(jù)的時(shí)候,同時(shí)更新緩存。Hibernate 二級(jí)緩存策略,是針對(duì)于 ID 查詢的緩存策略,對(duì)于條件查詢則毫無(wú)作用,為此,Hibernate 提供了針對(duì)條件查詢的Query Cache 查詢緩存
  • 二級(jí)緩存的并發(fā)訪問策略
    • 事務(wù)型:隔離級(jí)別最高 —— 適用于經(jīng)常被讀,很少修改的數(shù)據(jù)。可以防止臟讀和不可重讀的并發(fā)問題
    • 讀寫型:提供了 Read Commited 事務(wù)隔離級(jí)別 —— 適用于經(jīng)常被讀,很少修改的數(shù)據(jù)??梢苑乐古K讀
    • 非嚴(yán)格讀寫型:適用于應(yīng)用程序只是偶爾更新的數(shù)據(jù)
    • 只讀型:隔離級(jí)別最低 —— 適用于重來不會(huì)修改的數(shù)據(jù)
  • 適合放置在二級(jí)緩存的數(shù)據(jù)
    • 很少被修改的數(shù)據(jù)
    • 不是很重要的數(shù)據(jù),允許出現(xiàn)偶爾并發(fā)的數(shù)據(jù)
    • 不會(huì)被并發(fā)訪問的數(shù)據(jù)
    • 參考數(shù)據(jù) —— 指的是供應(yīng)用參考的常量數(shù)據(jù),它的實(shí)例數(shù)目有限,它的實(shí)例會(huì)被許多其他類的實(shí)例引用,實(shí)例極少或者從來不會(huì)被修改
  • 不適合存放到第二級(jí)緩存的數(shù)據(jù)
    • 經(jīng)常被修改的數(shù)據(jù)
    • 財(cái)務(wù)數(shù)據(jù),絕對(duì)不允許出現(xiàn)并發(fā)
    • 與其他應(yīng)用共享的數(shù)據(jù)
  • 二級(jí)緩存的使用
    • 添加對(duì)應(yīng)的二級(jí)緩存 jar 包
    • Hibernate 配置文件
      <!-- 開啟二級(jí)緩存 -->
      <property name="hibernate.cache.use_second_level_cache">true</property>
      <!-- 設(shè)置二級(jí)緩存實(shí)現(xiàn)類 -->
      <!-- 常見的有 EhCache 、OSCache 、SwarmCache 、JBossCache 等 -->
      <property name="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</property>
      
    • 選擇需要使用二級(jí)緩存的持久化類,設(shè)置它的命名緩存的并發(fā)訪問策略
      在映射文件中,在 <class> 的子元素下添加
      <!-- 配置二級(jí)緩存 -->
      <!-- usage 屬性,指二級(jí)緩存策略,有:read-only / read-write / nonstrict-read-write(不嚴(yán)格讀寫緩存) / transcational(事務(wù)性緩存) -->
      <!-- region 屬性,指定二級(jí)緩存的去域名,默認(rèn)為類或者集合的名字 -->
      <!-- include 屬性,all 包含所有屬性,non-lazy 僅包含非延遲加載的屬性 -->
      <cache usage="read-only" />
      
    • 新建緩存配置文件:ehcache.xml
      <ehcache>
          <!-- Sets the path to the directory where cache .data files are created.
      
               If the path is a Java System Property it is replaced by
               its value in the running VM.
      
               The following properties are translated:
               user.home - User's home directory
               user.dir - User's current working directory
               java.io.tmpdir - Default temp file path -->
          <diskStore path="/Users/slw/Documents/"/>
      
      
          <!--Default Cache configuration. These will applied to caches programmatically created through
              the CacheManager.
      
              The following attributes are required for defaultCache:
      
              maxInMemory       - Sets the maximum number of objects that will be created in memory
              eternal           - Sets whether elements are eternal. If eternal,  timeouts are ignored and the element
                                  is never expired.
              timeToIdleSeconds - Sets the time to idle for an element before it expires. Is only used
                                  if the element is not eternal. Idle time is now - last accessed time
              timeToLiveSeconds - Sets the time to live for an element before it expires. Is only used
                                  if the element is not eternal. TTL is now - creation time
              overflowToDisk    - Sets whether elements can overflow to disk when the in-memory cache
                                  has reached the maxInMemory limit.
      
              -->
          <defaultCache
              maxElementsInMemory="10000"
              eternal="false"
              timeToIdleSeconds="120"
              timeToLiveSeconds="120"
              overflowToDisk="true"
              />
      
          <!--Predefined caches.  Add your cache configuration settings here.
              If you do not have a configuration for your cache a WARNING will be issued when the
              CacheManager starts
      
              The following attributes are required for defaultCache:
      
              name              - Sets the name of the cache. This is used to identify the cache. It must be unique.
              maxInMemory       - Sets the maximum number of objects that will be created in memory
              eternal           - Sets whether elements are eternal. If eternal,  timeouts are ignored and the element
                                  is never expired.
              timeToIdleSeconds - Sets the time to idle for an element before it expires. Is only used
                                  if the element is not eternal. Idle time is now - last accessed time
              timeToLiveSeconds - Sets the time to live for an element before it expires. Is only used
                                  if the element is not eternal. TTL is now - creation time
              overflowToDisk    - Sets whether elements can overflow to disk when the in-memory cache
                                  has reached the maxInMemory limit.
      
              -->
      
          <!-- Sample cache named sampleCache1
              This cache contains a maximum in memory of 10000 elements, and will expire
              an element if it is idle for more than 5 minutes and lives for more than
              10 minutes.
      
              If there are more than 10000 elements it will overflow to the
              disk cache, which in this configuration will go to wherever java.io.tmp is
              defined on your system. On a standard Linux system this will be /tmp"
              -->
          <cache name="com.lian.entity.Account"
              maxElementsInMemory="10000"
              eternal="false"
              timeToIdleSeconds="300"
              timeToLiveSeconds="600"
              overflowToDisk="true"
              />
      
           <!-- 設(shè)置默認(rèn)的查詢緩存區(qū)域的屬性 -->
          <cache name="org.hibernate.cache.StandardQueryCache" 
              maxElementsInMemory="50"
              eternal="false" 
              timeToIdleSeconds="3600" 
              timeToLiveSeconds="7200" 
              overflowToDisk="true"/>
          <!-- 設(shè)置時(shí)間戳緩存區(qū)域的屬性 -->
          <cache name="org.hibernate.cache.UpdateTimestampsCache" 
              maxElementsInMemory="5000"
              eternal="true" 
              overflowToDisk="true"/> 
          <!-- 設(shè)置自定義命名查詢緩存區(qū)域的屬性,一般可不配置 -->
          <cache name="myCacheRegion"
              maxElementsInMemory="1000"
              eternal="false"
              timeToIdleSeconds="300"
              timeToLiveSeconds="600"
              overflowToDisk="true"/>
      </ehcache>
      

查詢緩存

  • 對(duì)于某個(gè)條件查詢語(yǔ)句經(jīng)常使用相同的條件值進(jìn)行查詢,就可以啟用查詢緩存

  • 只有當(dāng)經(jīng)常使用同樣的參數(shù)值進(jìn)行條件查詢時(shí),才起作用(查詢緩存緩存的 key 為 hql 或 sql )。所以,大多數(shù)查詢沒有必要使用查詢緩存

  • 查詢緩存的使用

    • Hibernate 配置文件
      <!-- 打開查詢緩存 -->
      <property name="hibernate.cache.use_query_cache">true</property>
      
    • 使用
      // 條件查詢
      String hql="from Account where name like :lname";
      Query query=session.createQuery(hql);
      query.setString("lname", "zhang%");
      
      // 啟用查詢緩存
      query.setCacheable(true);
      
      //指定所使用的查詢緩存策略
      query.setCacheRegion("myCacheRegion");
      
      List<Account> list=(List<Account>)query.list();
      
  • SessionFactory 對(duì)象的 getCache 方法返回一個(gè) Cache 對(duì)象

  • 開啟二級(jí)緩存的統(tǒng)計(jì)功能

    • 在 Hibernate 的配置文件中添加
      <property name="hibernate.generate_statistics">true</property>
      <property name="hibernate.cache.use_structured_entries">true</property>
      
    • sessionFactory.getStatistics().getSecondLevelCacheStatistics("持久化類完整路徑") 方法返回的對(duì)象提供一些工具可分析二級(jí)緩存效果

在 JTA 環(huán)境使用緩存策略(未完成)

在集群環(huán)境使用緩存策略(未完成)

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 1. Java基礎(chǔ)部分 基礎(chǔ)部分的順序:基本語(yǔ)法,類相關(guān)的語(yǔ)法,內(nèi)部類的語(yǔ)法,繼承相關(guān)的語(yǔ)法,異常的語(yǔ)法,線程的語(yǔ)...
    子非魚_t_閱讀 34,652評(píng)論 18 399
  • 一. Java基礎(chǔ)部分.................................................
    wy_sure閱讀 4,011評(píng)論 0 11
  • Hibernate是一個(gè)開放源代碼的對(duì)象關(guān)系映射框架,它對(duì)JDBC進(jìn)行了非常輕量級(jí)的對(duì)象封裝,它將POJO與數(shù)據(jù)庫(kù)...
    蘭緣小妖閱讀 1,276評(píng)論 1 18
  • 1. 簡(jiǎn)介 1.1 什么是 MyBatis ? MyBatis 是支持定制化 SQL、存儲(chǔ)過程以及高級(jí)映射的優(yōu)秀的...
    笨鳥慢飛閱讀 6,227評(píng)論 0 4
  • 這部分主要是開源Java EE框架方面的內(nèi)容,包括Hibernate、MyBatis、Spring、Spring ...
    雜貨鋪老板閱讀 1,556評(píng)論 0 2

友情鏈接更多精彩內(nèi)容