hibernate-memcached--在Hibernate中使用Memcached作为一个二级分布式缓存

今天在网上看到一个用Memcached作为Hibernate二级分布式缓存,感觉挺有兴趣,就是尝试用了,感觉还不错,就推荐给大家看一下。

官方网址:http://code.google.com/p/hibernate-memcached/

目前最新版本为1.0,支持Hibernate3.3.

下面是具体的使用方法:

hibernate-memcached需要支持的类库如下:

hibernate-memcached-<version>.jarmemcached-2.1.jarspy-2.4.jarcommons-codec1.3slf4j-1.5.0.jar如果你的项目使用的是Log4j,可以用slf4j-log4j12-1.5.0.jar

配置方法如下:

配置Hibernate使用cache提供类

hibernate.cache.provider_classcom.googlecode.hibernate.memcached.MemcachedCacheProvider

设置查询缓存开启

hibernate.cache.use_query_cachetrue

其它一些参数设置说明:PropertyDefaultDescriptionhibernate.memcached.serverslocalhost:11211memcached服务地址,多个用空格分隔

格式host:port

建议不要开启。

配置示例(本文以Hibernate3.3-entitymanager为例)

配置persistence.xml文件

<?xml version="1.0" encoding="UTF-8"?>

<persistencexmlns="http://java.sun.com/xml/ns/persistence""target="_new">http://java.sun.com/xml/ns/persistence"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://java.sun.com/xml/ns/persistencehttp://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"version="1.0">

<persistence-unitname="entityManager"transaction-type="RESOURCE_LOCAL">

<provider>org.hibernate.ejb.HibernatePersistence</provider>

<jta-data-source>java:comp/env/jdbc/qualitydb</jta-data-source>

<properties>

<propertyname="hibernate.dialect"value="org.hibernate.dialect.PostgreSQLDialect"/>

<propertyname="hibernate.max_fetch_depth"value="3"/>

<propertyname="hibernate.show_sql"value="true"/>

<propertyname="hibernate.cache.region_prefix"value="quality.cache.ehcache"/>

<propertyname="hibernate.cache.use_second_level_cache"value="true"/>

<propertyname="hibernate.cache.use_structured_entries"value="true"/>

<propertyname="hibernate.cache.use_query_cache"value="true"/>

<propertyname="hibernate.cache.provider_class"value="com.googlecode.hibernate.memcached.MemcachedCacheProvider"/>

<propertyname="hibernate.memcached.servers"value="localhost:11211"/>

</properties>

</persistence-unit>

</persistence>

启动后,提示如下:

2008-08-2817:10:08,312JCLLoggerAdapter.java265INFO--StartingMemcachedClient...

2008-08-2817:10:08.718INFOnet.spy.memcached.MemcachedConnection:Added{QAsa=localhost/127.0.0.1:11211,#Rops=0,#Wops=0,#iq=0,topRop=null,topWop=null,toWrite=0,interested=0}toconnectqueue

2008-08-2817:10:08.750INFOnet.spy.memcached.MemcachedConnection:Connectionstatechangedforsun.nio.ch.SelectionKeyImpl@16e59da

表示我们第一步配置已经成功了,接下来,对需要进行缓存的Entity进行配置

 1 @Entity

2@Cache(usage=CacheConcurrencyStrategy.READ_WRITE)//设置要求缓存

3publicclassStudent{

4

5@Id

6@Column(length=32)

7privateStringid;

8

9@Column(length=20)

10privatestringname;

11

12@OneToMany

13@Cache(usage=CacheConcurrencyStrategy.READ_WRITE)

14privateSet<Book>books;

15

16}

相关推荐