3

我有一个应用程序,它的后端是用 Spring 和 Hibernate 制作的。

我想应用内存缓存来使应用程序更具可扩展性。起初我以为我可以将hibernate的二级缓存与memcache集成,但问题是所有写在应用程序r中的HQL都像book.grade.id,其中Book和Grade是两个独立的实体,因此,二级缓存机制失败。

谁能推荐我一种实现缓存的方法?我看过 EHCache,但我现在想要 Memcache 实现。我的应用程序将受到多台服务器的攻击,但只会存在 1 个数据库服务器。鉴于所需条件,有什么建议吗?

4

1 回答 1

0

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

  1. pom.xml 更改为包含 memcache 的抽象缓存机制和使用 xmemcache 的客户端实现。

    com.google.code.simple-spring-memcached spring-cache 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(value="defaultCache", key="new Integer(#id).toString().concat('.BOOKVO')") public BookVO getBookById(Integer id){

    ... }

通过此更改,只有在内存缓存服务器中找不到密钥时,您的方法才会访问数据库。

于 2014-07-28T08:08:58.360 回答