现在的位置: 首页 > 综合 > 正文

java hibernate二级缓存

2013年03月05日 ⁄ 综合 ⁄ 共 5616字 ⁄ 字号 评论关闭

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

抱歉!评论已关闭.