少年阿賓

          那些青春的歲月

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

          常用鏈接

          留言簿(22)

          我參與的團(tuán)隊

          搜索

          •  

          最新評論

          閱讀排行榜

          評論排行榜

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

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

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

          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"<!--緩存是否永遠(yuǎn)不銷毀-->
                      overflowToDisk="true"<!--當(dāng)緩存中的數(shù)據(jù)達(dá)到最大值時,是否把緩存數(shù)據(jù)寫入磁盤-->
                      timeToIdleSeconds="15"<!--當(dāng)緩存閑置時間超過該值,則緩存自動銷毀-->
                          timeToLiveSeconds="120"<!--緩存創(chuàng)建之后,到達(dá)該緩存自動銷毀-->
                    />
                  </ehcache>
              4.2在Hibernate.cfg.xml中的mapping標(biāo)簽上面加以下內(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標(biāo)簽下加入以下內(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īng)用性能問題常見的原因,而緩存被廣泛的用于優(yōu)化數(shù)據(jù)庫應(yīng)用。cache被設(shè)計為通過保存從數(shù)據(jù)庫里load的數(shù)據(jù)來減少應(yīng)用和數(shù)據(jù) 庫之間的數(shù)據(jù)流動。數(shù)據(jù)庫訪問只有當(dāng)檢索的數(shù)據(jù)不在cache里可用時才必要。hibernate可以用兩種不同的對象緩存:first-level cache 和 second-level cache。first-level cache和Session對象關(guān)聯(lián),而second-level cache是和Session Factory對象關(guān)聯(lián)。

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

          下載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>
          說明:如果不設(shè)置“查詢緩存”,那么hibernate只會緩存使用load()方法獲得的單個持久化對象,如果想緩存使用findall()、 list()、Iterator()、createCriteria()、createQuery()等方法獲得的數(shù)據(jù)結(jié)果集的話,就需要設(shè)置 hibernate.cache.use_query_cache true 才行

          3.model類里采用Xdoclet生成*.hbm.xml里的cache xml標(biāo)簽,即<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的配置關(guān)系
          以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標(biāo)簽下面,其他位置無效。

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

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

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

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

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


          網(wǎng)站導(dǎo)航:
           
          主站蜘蛛池模板: 涿鹿县| 礼泉县| 那坡县| 伊吾县| 岐山县| 盖州市| 榆中县| 左云县| 鄂伦春自治旗| 遵化市| 庆安县| 高邮市| 三门县| 永定县| 乌拉特中旗| 宁城县| 刚察县| 临夏市| 四会市| 牡丹江市| 高碑店市| 阿合奇县| 遵义市| 沂源县| 河津市| 年辖:市辖区| 百色市| 辽阳县| 汕尾市| 叶城县| 昌乐县| 亚东县| 牙克石市| 博白县| 梁河县| 准格尔旗| 平阴县| 湖南省| 毕节市| 元谋县| 措美县|