ITeye博客

java中memcached作为hibernate的二级缓存

czykeith · 2012-07-27 11:01 · java · hibernate · memcached · 缓存 · 开源软件 · Markdown

因项目的问题,需要用到服务器缓存技术,我们选择了分布式的memcached来作为hibernate的二级缓存,需要用的的jar包如下:

memcached-2.1.jar hibernate-memcached-1.2.2.jar spy-2.4.jar

另外还需要下载memcached服务器

我是集成了spring的,所以首先在spring中加入如下配置

            <!-- 开启二级缓存 -->
            <prop key="hibernate.cache.use_second_level_cache">true</prop>
            <!-- 结构化方式存储 -->
            <prop key="hibernate.cache.use_structured_entries">true</prop>
            <!-- 查询缓存 -->
            <prop key="hibernate.cache.use_query_cache">true</prop>
            <!-- 二级缓存服务类 -->
            <prop key="hibernate.cache.provider_class">
                com.googlecode.hibernate.memcached.MemcachedCacheProvider
            </prop>
            <!-- 二级缓存服务地址和端口 -->
            <prop key="hibernate.memcached.servers">localhost:11211 127.0.0.1:11211</prop>
            <!--缓存时间-->
            <prop key="hibernate.memcached.operationTimeout">60000</prop>

这样我们就配置了memcached来作为hibernate的二级缓存,当然我们的配置还没有完成,仅仅这样配置缓存是不会工作

接下来我们需要在需要缓存的实体对象的映射文件中加入缓存标签,即在.hbm.xml中加入记住,此配置只能配置在class里面,且需要配置在id之前,当然usage的策略还有几种,我就不一一介绍了

当然如果你使用的是jpa就需要在实体上加上@Cache(usage = CacheConcurrencyStrategy.READ_WRITE) 的注解

如果你使用的是query的查询方式的话,你还需要做这样的设置query.setCacheable(true);

然后运行memcached 然后启动项目,如果看到一下信息,那么证明你配置成功了

2012-07-27 10:10:01.988 INFO net.spy.memcached.MemcachedConnection: Added {QA sa=localhost/127.0.0.1:11211, #Rops=0, #Wops=0, #iq=0, topRop=null, topWop=null, toWrite=0, interested=0} to connect queue 2012-07-27 10:10:01.988 INFO net.spy.memcached.MemcachedConnection: Added {QA sa=/127.0.0.1:11211, #Rops=0, #Wops=0, #iq=0, topRop=null, topWop=null, toWrite=0, interested=0} to connect queue 2012-07-27 10:10:01.988 INFO net.spy.memcached.MemcachedConnection: Connection state changed for sun.nio.ch.SelectionKeyImpl@1a9447c 2012-07-27 10:10:01.988 INFO net.spy.memcached.MemcachedConnection: Connection state changed for sun.nio.ch.SelectionKeyImpl@1dba6e2

评论(2)

  1. #2 楼 · developerinit · 2013-03-03 22:26

    什么苦头?

  2. #1 楼 · dynamiclu · 2012-07-28 14:02

    兄弟,以后会有苦头吃!

评论功能维护中,当前仅展示历史评论。