发表时间:2009-03-30
最后修改:2009-04-01
入门使用cache很简单。
1/ 在 classpath根下建 ehcache.xml 内容如下:
<ehcache>
<diskStore path="java.io.tmpdir"/>
<defaultCache
maxElementsInMemory="10000"
eternal="false"
overflowToDisk="true"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
diskPersistent="false"
diskExpiryThreadIntervalSeconds="120"/>
</ehcache>
2/ 修改需要使用缓存的对象所对应的hbm.xml文件。加入 <cache usage="read-only"/>标记。
3/ 默认情况下,load是使用缓存的。 但一般是使用find或者list方法来取得数据。所以按如下操作:
修改 hibernate.cfg.xml 加入
<property name="show_sql">true</property>
<property name="hibernate.cache.use_query_cache">true</property>
<property name="hibernate.cache.use_second_level_cache">true</property>
<property name="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</property>
4/ 在DAO的代码中使用
Session session = sf.openSession();
try {
Query query = session.createQuery("from StockInfo where id = ?");
query.setLong(0, 1800);
query.setCacheable(true);
query.list();
session.close();
session = sf.openSession();
query = session.createQuery("from StockInfo where id = ?");
query.setLong(0, 1800);
query.setCacheable(true);
query.list();
} catch (Exception ex) {
log.info(ex.getMessage(), ex);
}
你会发现只会打印出一条SQL语句。 证明使用了缓存功能。
下面是关键的另一步了。 在系统中,由于程序的bug或者特殊情况需要直接修改数据库 而又不允许停机。 这时候,如果你的cache规则定义的好, 那么只影响那么几毫秒。 但有规则的定义未必那么全面。 这时候就需要:使用SQL语句修改后台数据库之后,需要清空application的缓存,从而让hibernate到数据库中取到最新的 修改之后的值
hibernate好像没有提供直接的清除cache的方法(我没找到)。所以使用下面的函数:
sf 是 application中的sessionfactory。
public static void evictSecondLevelCache() {
Map<String, CollectionMetadata> roleMap = sf.getAllCollectionMetadata();
for (String roleName : roleMap.keySet()) {
sf.evictCollection(roleName);
}
Map<String, ClassMetadata> entityMap = sf.getAllClassMetadata();
for (String entityName : entityMap.keySet()) {
sf.evictEntity(entityName);
}
sf.evictQueries();
}
示例:
Session session = sf.openSession();
try {
Query query = session.createQuery("from StockInfo where id = ?");
query.setLong(0, 1800);
query.setCacheable(true);
query.list();
session.close();
evictSecondLevelCache();
session = sf.openSession();
query = session.createQuery("from StockInfo where id = ?");
query.setLong(0, 1800);
query.setCacheable(true);
query.list();
} catch (Exception ex) {
log.info(ex.getMessage(), ex);
}
就会在控制台中发现打印出两条SQL语句。 实际中可以把 evictSecondLevelCache();
放到一个单独的管理页面中。 叫“清除缓存”功能。 专门为 手动修改数据库 后的数据同步做准备。