<rt id="bn8ez"></rt>
<label id="bn8ez"></label>

  • <span id="bn8ez"></span>

    <label id="bn8ez"><meter id="bn8ez"></meter></label>

    少年阿賓

    那些青春的歲月

      BlogJava :: 首頁 :: 聯(lián)系 :: 聚合  :: 管理
      500 Posts :: 0 Stories :: 135 Comments :: 0 Trackbacks

    1.EhCache是什么
        EhCache是Hibernate的二級緩存技術之一,可以把查詢出來的數(shù)據(jù)存儲在內(nèi)存或者磁盤,節(jié)省下次同樣查詢語句再次查詢數(shù)據(jù)庫,大幅減輕數(shù)據(jù)庫壓力;

    2.EhCache的使用注意點
        當用Hibernate的方式修改表數(shù)據(jù)(save,update,delete等等),這時EhCache會自動把緩存中關于此表的所有緩存全部刪除掉(這樣能達到同步)。但對于數(shù)據(jù)經(jīng)常修改的表來說,可能就失去緩存的意義了(不能減輕數(shù)據(jù)庫壓力);

    3.EhCache使用的場合
        3.1比較少更新表數(shù)據(jù)
            EhCache一般要使用在比較少執(zhí)行write操作的表(包括update,insert,delete等)[Hibernate的二級緩存也都是這樣];
        3.2對并發(fā)要求不是很嚴格的情況
            兩臺機子中的緩存是不能實時同步的;

    4.在項目做的實現(xiàn)
        4.1在工程的src目錄下添加ehcache.xml文件,內(nèi)容如下:
            <?xml version="1.0" encoding="UTF-8"?>
            <ehcache>    
                <diskStore path="java.io.tmpdir" />
              <defaultCache maxElementsInMemory="5"<!--緩存可以存儲的總記錄量-->
                eternal="false"<!--緩存是否永遠不銷毀-->
                overflowToDisk="true"<!--當緩存中的數(shù)據(jù)達到最大值時,是否把緩存數(shù)據(jù)寫入磁盤-->
                timeToIdleSeconds="15"<!--當緩存閑置時間超過該值,則緩存自動銷毀-->
                    timeToLiveSeconds="120"<!--緩存創(chuàng)建之后,到達該緩存自動銷毀-->
              />
            </ehcache>
        4.2在Hibernate.cfg.xml中的mapping標簽上面加以下內(nèi)容:

            <property name="show_sql">true</property>
            <property name="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</property>
            <property name="hibernate.cache.use_query_cache">true</property>
        4.3在要緩存的bean的hbm.xml文件中的class標簽下加入以下內(nèi)容:
           <cache usage="read-only" /><!--也可讀寫-->
        4.4創(chuàng)建DAO,內(nèi)容如下:
            Session s = HibernateSessionFactory.getSession();
            Criteria c = s.createCriteria(Xyz.class);
            c.setCacheable(true);//這句必須要有
            System.out.println("第一次讀取");
            List l = c.list();
            System.out.println(l.size());
            HibernateSessionFactory.closeSession();

            s = HibernateSessionFactory.getSession();
            c = s.createCriteria(Xyz.class);
            c.setCacheable(true);//這句必須要有
            System.out.println("第二次讀取");
            l = c.list();
            System.out.println(l.size());
            HibernateSessionFactory.closeSession();
       4.5這時你會看到打印出來的信息為(表示第二次并沒有去讀庫):
            第一次讀取
            Hibernate: *******
            13
            第二次讀取
            13

    配置Spring+hibernate使用ehcache作為second-level cache

    大量數(shù)據(jù)流動是web應用性能問題常見的原因,而緩存被廣泛的用于優(yōu)化數(shù)據(jù)庫應用。cache被設計為通過保存從數(shù)據(jù)庫里load的數(shù)據(jù)來減少應用和數(shù)據(jù) 庫之間的數(shù)據(jù)流動。數(shù)據(jù)庫訪問只有當檢索的數(shù)據(jù)不在cache里可用時才必要。hibernate可以用兩種不同的對象緩存:first-level cache 和 second-level cache。first-level cache和Session對象關聯(lián),而second-level cache是和Session Factory對象關聯(lián)。

            缺省地,hibernate已經(jīng)使用基于每個事務的first-level cache。 Hibernate用first-level cache主要是減少在一個事務內(nèi)的sql查詢數(shù)量。例如,如果一個對象在同一個事務內(nèi)被修改多次,hibernate將只生成一個包括所有修改的 UPDATE SQL語句。為了減少數(shù)據(jù)流動,second-level cache在Session Factory級的不同事務之間保持load的對象,這些對象對整個應用可用,不只是對當前用戶正在運行的查詢。這樣,每次查詢將返回已經(jīng)load在緩存 里的對象,避免一個或更多潛在的數(shù)據(jù)庫事務。

    下載ehcache,hibernate3.2必須要ehcache1.2以上才能支持。可以修改log4j配置文件log4j.logger.net.sf.hibernate.cache=debug查看日志

    1.在類路徑上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="java.io.tmpdir"/>


         <!--Default Cache configuration. These will applied to caches programmatically created through
             the CacheManager.

             The following attributes are required:

             maxElementsInMemory             - 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.
             overflowToDisk                  - Sets whether elements can overflow to disk when the in-memory cache
                                              has reached the maxInMemory limit.

             The following attributes are optional:
             timeToIdleSeconds               - Sets the time to idle for an element before it expires.
                                              i.e. The maximum amount of time between accesses before an element expires
                                              Is only used if the element is not eternal.
                                              Optional attribute. A value of 0 means that an Element can idle for infinity.
                                              The default value is 0.
             timeToLiveSeconds               - Sets the time to live for an element before it expires.
                                              i.e. The maximum time between creation time and when an element expires.
                                              Is only used if the element is not eternal.
                                              Optional attribute. A value of 0 means that and Element can live for infinity.
                                              The default value is 0.
             diskPersistent                  - Whether the disk store persists between restarts of the Virtual Machine.
                                              The default value is false.
             diskExpiryThreadIntervalSeconds- The number of seconds between runs of the disk expiry thread. The default value
                                              is 120 seconds.
             -->

         <defaultCache
             maxElementsInMemory="10000"
             eternal="false"
             overflowToDisk="true"
             timeToIdleSeconds="120"
             timeToLiveSeconds="120"
             diskPersistent="false"
             diskExpiryThreadIntervalSeconds="120"/>
            
         <!-- See http://ehcache.sourceforge.net/documentation/#mozTocId258426 for how to configure caching for your objects -->
    </ehcache>

    2.applicationContext-hibernate.xml里Hibernate SessionFactory配置:

         <!-- Hibernate SessionFactory -->
         <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
             <property name="dataSource" ref="dataSource"/>
             <property name="configLocation"><value>classpath:hibernate.cfg.xml</value></property>
             <!-- The property below is commented out b/c it doesn't work when run via
                  Ant in Eclipse.   It works fine for individual JUnit tests and in IDEA ??
             <property name="mappingJarLocations">
                 <list><value>file:dist/appfuse-dao.jar</value></list>
             </property>
             -->
             <property name="hibernateProperties">
                 <props>
                     <prop key="hibernate.dialect">@HIBERNATE-DIALECT@</prop>
                     <!--<prop key="hibernate.show_sql">true</prop>-->
                     <prop key="hibernate.max_fetch_depth">3</prop>
                     <prop key="hibernate.hibernate.use_outer_join">true</prop>
                     <prop key="hibernate.jdbc.batch_size">10</prop>
                     <prop key="hibernate.cache.use_query_cache">true</prop>
                     <prop key="hibernate.cache.use_second_level_cache">true</prop>
                     <prop key="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</prop>
                     <!--
                     <prop key="hibernate.use_sql_comments">false</prop>
                     -->
                     <!-- Create/update the database tables automatically when the JVM starts up
                     <prop key="hibernate.hbm2ddl.auto">update</prop> -->
                     <!-- Turn batching off for better error messages under PostgreSQL
                     <prop key="hibernate.jdbc.batch_size">0</prop> -->
                 </props>
             </property>
             <property name="entityInterceptor">
                <ref local="auditLogInterceptor"/>
             </property>
         </bean>
    說明:如果不設置“查詢緩存”,那么hibernate只會緩存使用load()方法獲得的單個持久化對象,如果想緩存使用findall()、 list()、Iterator()、createCriteria()、createQuery()等方法獲得的數(shù)據(jù)結果集的話,就需要設置 hibernate.cache.use_query_cache true 才行

    3.model類里采用Xdoclet生成*.hbm.xml里的cache xml標簽,即<cache usage="read-only"/>

    /**
    * @hibernate.class table="WF_WORKITEM_HIS"
    * @hibernate.cache usage="read-write"
    *
    */

    4.對于"query cache",需要在程序里編碼:

             getHibernateTemplate().setCacheQueries(true);
             return getHibernateTemplate().find(hql);

     

     

    使用spring和hibernate配置ehcache和query cache
     
    1、applicationContext.xml
    <prop key="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</prop>
    <prop key="hibernate.cache.use_query_cache">true</prop>

    這兩句加到hibernateProperties中
    <bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
    <property name="sessionFactory">
       <ref bean="sessionFactory" />
    </property>
    <property name="cacheQueries">
       <value>true</value>
    </property>
    </bean>

    添加此bean到applicationcontext.xml中。在各個DAO的bean中,更改如下
    <property name="sessionFactory">
    <ref bean="sessionFactory" />
    </property>
    改為
    <property name="hibernateTemplate">
    <ref bean="hibernateTemplate" />
    </property>

    2、ehcache.xml文件放在classes根目錄即可

    3、pojo與ehcache.xml的配置關系
    以com.ce.ceblog.pojos.CeblogJournal為例子
    在CeblogJournal.hbm.xml中配置:
    <class name="CeblogJournal" table="CEBLOG_JOURNAL" lazy="false">
    <cache usage="read-write" region="ehcache.xml中的name的屬性值"/>
    注意:這一句需要緊跟在class標簽下面,其他位置無效。

    Ehcache.xml文件主體如下
    <defaultCache maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="1" timeToLiveSeconds="1" overflowToDisk="true" />
    <cache name="com.ce.ceblog.pojos.CeblogJournal" maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="300" timeToLiveSeconds="600" overflowToDisk="true" />
    hbm文件查找cache方法名的策 略:如果不指定hbm文件中的region="ehcache.xml中的name的屬性值",則使用name名為 com.ce.ceblog.pojos.CeblogJournal的cache,如果不存在與類名匹配的cache名稱,則用 defaultCache。
    如果CeblogJournal包含set集合,則需要另行指定其cache
    例如CeblogJournal包含ceblogReplySet集合,則需要
    添加如下配置到ehcache.xml中
    <cache name="com.ce.ceblog.pojos.CeblogJournal.ceblogReplySet"
    maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="300"
    timeToLiveSeconds="600" overflowToDisk="true" />

    另,針對查詢緩存的配置如下:
    <cache name="org.hibernate.cache.UpdateTimestampsCache"
    maxElementsInMemory="5000"
    eternal="true"
    overflowToDisk="true"/>
    <cache name="org.hibernate.cache.StandardQueryCache"
    maxElementsInMemory="10000"
    eternal="false"
    timeToLiveSeconds="120"
    overflowToDisk="true"/>

    4、選擇緩存策略依據(jù):
    <cache usage="transactional|read-write|nonstrict-read-write|read-only" />
    ehcache不支持transactional,其他三種可以支持。
    read- only:無需修改, 那么就可以對其進行只讀 緩存,注意,在此策略下,如果直接修改數(shù)據(jù)庫,即使能夠看到前臺顯示效果,但是將對象修改至cache中會報error,cache不會發(fā)生作用。另:刪 除記錄會報錯,因為不能在read-only模式的對象從cache中刪除。
    read-write:需要更新數(shù)據(jù),那么使用讀/寫緩存 比較合適,前提:數(shù)據(jù)庫不可以為serializable transaction isolation level(序列化事務隔離級別)
    nonstrict-read-write:只偶爾需要更新數(shù)據(jù)(也就是說,兩個事務同時更新同一記錄的情況很不常見),也不需要十分嚴格的事務隔離,那么比較適合使用非嚴格讀/寫緩存策略。

    5、調(diào)試時候使用log4j的log4j.logger.org.hibernate.cache=debug,更方便看到ehcache的操作過程,主要用于調(diào)試過程,實際應用發(fā)布時候,請注釋掉,以免影響性能。

    6、 使用ehcache,打印sql語句是正常的,因為query cache設置為true將會創(chuàng)建兩個緩存區(qū)域:一個用于保存查詢結果集 (org.hibernate.cache.StandardQueryCache); 另一個則用于保存最近查詢的一系列表的時間戳(org.hibernate.cache.UpdateTimestampsCache)。請注意:在查詢 緩存中,它并不緩存結果集中所包含的實體的確切狀態(tài);它只緩存這些實體的標識符屬性的值、以及各值類型的結果。需要將打印sql語句與最近的cache內(nèi) 容相比較,將不同之處修改到cache中,所以查詢緩存通常會和二級緩存一起使用。

    posted on 2012-05-13 02:08 abin 閱讀(318) 評論(0)  編輯  收藏

    只有注冊用戶登錄后才能發(fā)表評論。


    網(wǎng)站導航:
     
    主站蜘蛛池模板: 亚洲一区二区中文| 特级av毛片免费观看| 国产成人在线观看免费网站| 男女猛烈无遮掩视频免费软件| 一本色道久久综合亚洲精品| 中文免费观看视频网站| 羞羞漫画页面免费入口欢迎你| 亚洲成AV人片在线观看WWW| 99精品国产免费久久久久久下载| 老司机午夜在线视频免费| 亚洲人成电影在在线观看网色| 免费爱爱的视频太爽了| a毛片免费全部播放完整成| 亚洲精品福利你懂| 亚洲欧洲日产国码av系列天堂| 四虎国产精品免费久久| 丝瓜app免费下载网址进入ios| 亚洲乱人伦精品图片| 国产亚洲AV手机在线观看| 最近的中文字幕大全免费版| 免费人成激情视频在线观看冫| 亚洲乱色熟女一区二区三区蜜臀| 亚洲s色大片在线观看| 国产大片91精品免费看3| 在线观看免费av网站| 国产VA免费精品高清在线| 亚洲乱码在线观看| 亚洲国产第一页www| 亚洲精品国产精品乱码不卡| 成人五级毛片免费播放| 日韩免费无码视频一区二区三区| 深夜特黄a级毛片免费播放| 亚洲AV无码国产精品色| 亚洲AV无码国产丝袜在线观看| 亚洲第一永久AV网站久久精品男人的天堂AV| 最近中文字幕电影大全免费版 | 伊人久久综在合线亚洲2019| 免费在线观看黄网站| 女人18毛片水真多免费看| 亚洲一区免费在线观看| 无码日韩精品一区二区三区免费|