2013-06-26 105 views
3

我有一個應用程序,其後端已經使用Spring和Hibernate進行了開發。使用Memcached進行Spring-Hibernate緩存

我想應用memcaching使應用程序更具可擴展性。起初我認爲我可以將hibernate的二級緩存與memcache集成在一起,但問題引起的一個問題是,所有在應用程序中寫入的HQL都像book.grade.id那樣,Book & Grade是兩個獨立的實體,因此第二級緩存機制失敗。

任何人都可以推薦一種方法來實現緩存?我曾看過EHCache,但我現在需要Memcache實施。我的應用程序將受到多個服務器的影響,但只有1個數據庫服務器存在。鑑於所需的條件,任何建議?

回答

0

下面提到的是您可以遵循的步驟。

  1. pom.xml更改爲包含使用xmemcache的memcache和客戶端實現的抽象緩存機制。

    com.google.code.simple-彈簧的memcached 彈簧緩存 3.1.0

    <dependency> 
        <groupId>com.google.code.simple-spring-memcached</groupId> 
        <artifactId>xmemcached-provider</artifactId> 
        <version>3.1.0</version> 
    </dependency> 
    

注意:您需要包括CGLIB過,因爲這是基於AOP。

  1. configuration.xml配置文件更改

**defining beans** 

    <bean name="cacheManager" class="com.google.code.ssm.spring.SSMCacheManager"> 
<property name="caches"> 
    <set> 
     <bean class="com.google.code.ssm.spring.SSMCache"> 
      <constructor-arg name="cache" index="0" ref="defaultCache"/> 
      <!-- 5 minutes --> 
      <constructor-arg name="expiration" index="1" value="300"/> 
      <!-- @CacheEvict(..., "allEntries" = true) doesn't work --> 
      <constructor-arg name="allowClear" index="2" value="false"/> 
     </bean> 
    </set> 
</property> 

</bean> 


<bean name="defaultCache" class="com.google.code.ssm.CacheFactory"> 
    <property name="cacheName" value="defaultCache" /> 
    <property name="cacheClientFactory"> 
     <bean name="cacheClientFactory" 
      class="com.google.code.ssm.providers.xmemcached.MemcacheClientFactoryImpl" /> 
    </property> 
    <property name="addressProvider"> 
     <bean class="com.google.code.ssm.config.DefaultAddressProvider"> 
      <property name="address" value="x.x.x.x:11211" /> 
     </bean> 
    </property> 
    <property name="configuration"> 
     <bean class="com.google.code.ssm.providers.CacheConfiguration"> 
      <property name="consistentHashing" value="true" /> 
     </bean> 
    </property> 

</bean> 
  1. 的抽樣方法...

    @Cacheable(值= 「defaultCache」 鍵=「新的整數(#id).toString()。concat('。BOOKVO')「) public BookVO getBookById(Integer id){

    ... }

這種改變你的方法只命中瞭如果該鍵沒有在內存緩存服務器中發現的數據庫。