EHCache的使用场合
1比较少更新表数据
EhCache一般要使用在比较少执行write操作的表(包括update,insert,delete等)[Hibernate的二级缓存也都是这样];
2 对并发要求不是很严格的情况
两台机子中的缓存是不能实时同步的;
这是一个简单的 ehcache 对象缓存 例子
ehcache 对象缓存 的配置
hibernate配置文件
<session-factory>
<property name="connection.username">root</property>
<property name="connection.url">
jdbc:mysql://localhost/test
</property>
<property name="dialect">
org.hibernate.dialect.MySQLDialect
</property>
<property name="myeclipse.connection.profile">mysql</property>
<property name="connection.password">root</property>
<property name="connection.driver_class">
com.mysql.jdbc.Driver
</property>
<property name="hbm2ddl.auto">update</property>
<property name="show_sql">true</property>
<!-- 设置Hibernate的缓存接口类,这个类在Hibernate包中 -->
<property name="cache.provider_class">org.hibernate.cache.EhCacheProvider</property>
<!-- 是否启用查询缓存 -->
<property name="cache.use_query_cache">true</property>
<mapping resource="com/cache/entity/User.hbm.xml" />
</session-factory>
ehcache.xml 配置
<defaultCache
maxElementsInMemory="10000"
eternal="false"
overflowToDisk="true"
timeToIdleSeconds="300"
timeToLiveSeconds="180"
diskPersistent="false"
diskExpiryThreadIntervalSeconds= "120">
</defaultCache>
在src 下放入 ehcache.xml、ehcache.xsd
java代码:
/**
* @{#} 类名称: EhCache.java
* 创建时间: Aug 31, 2009 2:31:05 PM
*
*/
package com.cache.test;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import com.cache.utils.HibernateSessionFactory;
/**
* @作者 <a href="http://qing393260529.iteye.com">黎青春</a>
* @版本 1.0
*/
public class EhCache {
public static void main(String[] args) {
Session s = HibernateSessionFactory.getSession();
Query query =s.createQuery("from User");
query.setCacheable(true); //这句必须要有
System.out.println("第一次读取");
List l = query.list();
System.out.println(l.size());
HibernateSessionFactory.closeSession();
s = HibernateSessionFactory.getSession();
query = s.createQuery("from User");
query.setCacheable(true); //这句必须要有
System.out.println("第二次读取");
l = query.list();
System.out.println(l.size());
HibernateSessionFactory.closeSession();
}
}