java hibernate二級緩存

hibernate的二級緩存由第三方插件提供,比如EhCache、OsCache、SwarmCache及JBossTreeCache等,在本文中,只會對EhCache的配置作簡介。
  首先要明確一點,並不是所有類都應該使用二級緩存,經常讀取而修改比較少的類才適合使用二級緩存的,我們一定要對啓用二級緩存的類分析清楚。
  要使用二級緩存,主要有兩步工作:
  1.爲相應的類選擇合併的併發策略;
  2.配置第三方緩存插件。

  1.併發訪問策略
   1.1只讀(read-only): 對於永遠不會被修改的數據可以採用這種併發訪問策略,它的併發性能是最高的。但必須保證數據不會被修改,否則就會出錯。
    1.2非嚴格讀寫(nonstrict-read-write): 非嚴格讀寫不能保證緩存與數據庫中數據的一致性,如果存在兩個事務併發地訪問緩存數據的可能,則應該爲該數據配置一個很短的過期時間,以減少讀髒數據的可能。對於極少被修改,並且可以容忍偶爾髒讀的數據可以採用這種併發策略。
    1.3讀寫(read-write): 讀寫策略提供了“read committed"數據庫隔離級別。對於經常被讀但很少修改的數據可以採用這種策略,它可以防止讀髒數據。
    1.4事務(transactional): 它提供了Repeatable Read事務隔離級別。它可以防止髒讀和不可重複讀這類的併發問題。

   在這裏,只讀是性能最高的二級緩存,越往後二級緩存在性能上的提高越低。EhCache是不支持事務級的併發策略。

   例如:我們指定Category類使用read-write策略
   @Entity
   @Table(name = "CATEGORY")
   @org.hibernate.annotations.Cache(usage =
         org.hibernate.annotations.CacheConcurrencyStrategy.READ_WRITE
    )
    public class Category { ... }


  2.配置第三方緩存插件
     設置provider:
     hibernate.cache.provider_class = org.hibernate.cache.EhCacheProvider
     設置開啓二級緩存:
     hibernate.cache.use_second_level_cache=true
     如果有多個SessionFactory,則需要設置相應的緩衝區域前綴:
     hibernate.cache.region_prefix=db1

     在ehcache.xml配置文件中,對緩衝的類進行相應的設置,如下例所示:
    <cache name="auction.model.Category"
                 maxElementsInMemory="500"
                 eternal="true"
                 timeToIdleSeconds="0"
                 timeToLiveSeconds="0"
                overflowToDisk="false"
      />
      name對應的是緩衝區域名,在單個SessionFactory情況下,它就是類的全路徑名稱,如果有前綴則加上前綴,例如:db1.auction.model.Category
     etermal指的是即使過期都仍然在緩存中;
     timeToIdleSeconds,對象進入緩存後,最後一次被使用後,空閒的時間間隔,超過時間即認爲過期;

     timeToLiveSeconds,從對象進入緩存開始算,在緩存中的存活時間,超過該時間,即認爲過期;

ehcache.txt   內容如下:

<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="java.io.tmpdir"/>


    <!--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="sampleCache1"
        maxElementsInMemory="10000"
        eternal="false"
        timeToIdleSeconds="300"
        timeToLiveSeconds="600"
        overflowToDisk="true"
        />

    <!-- Sample cache named sampleCache2
        This cache contains 1000 elements. Elements will always be held in memory.
        They are not expired. -->
    <cache name="sampleCache2"
        maxElementsInMemory="1000"
        eternal="true"
        timeToIdleSeconds="0"
        timeToLiveSeconds="0"
        overflowToDisk="false"
        /> -->

    <!-- Place configuration for your caches following -->

</ehcache>
log4j.txt  內容如下:
### direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

### direct messages to file hibernate.log ###
#log4j.appender.file=org.apache.log4j.FileAppender
#log4j.appender.file.File=hibernate.log
#log4j.appender.file.layout=org.apache.log4j.PatternLayout
#log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

### set log levels - for more verbose logging change 'info' to 'debug' ###

log4j.rootLogger=warn, stdout

#log4j.logger.org.hibernate=info
log4j.logger.org.hibernate=debug

### log HQL query parser activity
#log4j.logger.org.hibernate.hql.ast.AST=debug

### log just the SQL
#log4j.logger.org.hibernate.SQL=debug

### log JDBC bind parameters ###
log4j.logger.org.hibernate.type=info
#log4j.logger.org.hibernate.type=debug

### log schema export/update ###
log4j.logger.org.hibernate.tool.hbm2ddl=debug

### log HQL parse trees
#log4j.logger.org.hibernate.hql=debug

### log cache activity ###
#log4j.logger.org.hibernate.cache=debug

### log transaction activity
#log4j.logger.org.hibernate.transaction=debug

### log JDBC resource acquisition
#log4j.logger.org.hibernate.jdbc=debug

### enable the following line if you want to track down connection ###
### leakages when using DriverManagerConnectionProvider ###
#log4j.logger.org.hibernate.connection.DriverManagerConnectionProvider=trace


發佈了65 篇原創文章 · 獲贊 93 · 訪問量 39萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章