【问题标题】:Spring-Hibernate Caching with Memcached使用 Memcached 进行 Spring-Hibernate 缓存
【发布时间】:2013-06-23 12:31:31
【问题描述】:

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

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

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

【问题讨论】:

    标签: spring hibernate caching memcached


    【解决方案1】:

    以下是您可以遵循的步骤。

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

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

      ... }

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-08-14
      • 2010-09-20
      • 1970-01-01
      • 1970-01-01
      • 2011-07-21
      • 1970-01-01
      • 2011-09-03
      相关资源
      最近更新 更多