Java項目開發心得(二):使用EhCache+SSM實現資料緩衝__Java

來源:互聯網
上載者:User

在項目的開發過程中,經常會考慮到提高使用者訪問效率,降低伺服器的壓力,這個時候會用到資料緩衝。當前實現緩衝的技術有很多,

例如: jCache、Ehcache以及快取服務器redis,redis作為分布式系統重要的組成部分,該技術的使用以及相關的一些問題會在後面的文章當中詳細介紹。

目前,我將要提到的就是Ehcache和Spring項目的整合實現緩衝。

前期的準備工作:(實體類、Dao、Service、Controller)、Ehcache的設定檔

EHCache的相關配置

<?xml version="1.0" encoding="utf-8"><ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"updateCheck="false"><diskStore path="java.io.tmpdir"><defaultCache eternal="false" maxElementsInMemory="1000"        overflowToDisk="false" diskPersistent="false" timeToIdleSeconds="0"        timeToLiveSeconds="600" memoryStoreEvictionPolicy="LRU" />    <cache name="testCache" eternal="false" maxElementsInMemory="100"        overflowToDisk="false" diskPersistent="false" timeToIdleSeconds="0"        timeToLiveSeconds="300" memoryStoreEvictionPolicy="LRU" /></ehcache>


並且,緊接著我們需要在applicationContext.xml中配置相關bean,具體如下:

<bean id="cacheManagerFactory" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"><!--找到ehcache.xml設定檔的位置-->    <property name="configLocation" value="classpath:ehcache.xml"/>     <property name="shared" value="true"></property></bean><bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager"><property name="cacheManager" ref="cacheManagerFactory"/></bean>


<!--開啟緩衝-->

<!--這裡尤其要注意的是mode的屬性,可選值有proxy和aspectj,預設為proxy。如果使用預設值,則緩衝方法只有在外部被調用的時候才能起到緩衝的作用。

並且當選擇mode="aspectj"以及proxy-target-class="true"時,它是直接基於class類操作的,此時定義在介面上的@Cacheable註解不會起作用

<cache:annotation-driven cache-manager="cacheManager" mode="aspectj" proxy-target-class="true">

然後是代碼方面:

<!--這裡的cacheNames選擇在ehcache.xml檔案中配置的cache-->

另外在mybatis相關的對應檔裡,也就是查詢語句的xml裡面,加上一句列印快取資料相關的日誌

<cache type="org.mybatis.caches.ehcache.LoggingEhcache"/>   

最後是運行後的截圖:

(第一次查詢,走資料庫查詢)



(第二次查詢,進入緩衝查詢)

  


目前的這個版本是我重新重現的結果,至於之前有讀者提到關於可能會出現new多個緩衝的問題,在ehcache2.5之後cacheManager就採用了sington,所以不會出現new多個的緩衝的出現,並且需要加上    <property name="shared" value="true"></property>,否則就會報錯

Ok,成功。以上就是關於Ehcache+Spring的相關配置,如果有問題,可直接留言給我,我們共同交流學習。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.