入門使用cache很簡單。
1/ 在 classpath根下建 ehcache.xml 內(nèi)容如下:
<ehcache>
<diskStore path="java.io.tmpdir"/>
<defaultCache
maxElementsInMemory="10000"
eternal="false"
overflowToDisk="true"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
diskPersistent="false"
diskExpiryThreadIntervalSeconds="120"/>
</ehcache>
2/ 修改需要使用緩存的對象所對應(yīng)的hbm.xml文件。加入 <cache usage="read-only"/>標(biāo)記。
3/ 默認(rèn)情況下,load是使用緩存的。 但一般是使用find或者list方法來取得數(shù)據(jù)。所以按如下操作:
修改 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);
}
你會發(fā)現(xiàn)只會打印出一條SQL語句。 證明使用了緩存功能。
下面是關(guān)鍵的另一步了。 在系統(tǒng)中,由于程序的bug或者特殊情況需要直接修改數(shù)據(jù)庫 而又不允許停機(jī)。 這時(shí)候,如果你的cache規(guī)則定義的好, 那么只影響那么幾毫秒。 但有規(guī)則的定義未必那么全面。 這時(shí)候就需要:使用SQL語句修改后臺數(shù)據(jù)庫之后,需要清空application的緩存,從而讓hibernate到數(shù)據(jù)庫中取到最新的 修改之后的值
hibernate好像沒有提供直接的清除cache的方法(我沒找到)。所以使用下面的函數(shù):
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);
}
就會在控制臺中發(fā)現(xiàn)打印出兩條SQL語句。 實(shí)際中可以把 evictSecondLevelCache();
放到一個(gè)單獨(dú)的管理頁面中。 叫“清除緩存”功能。 專門為 手動(dòng)修改數(shù)據(jù)庫 后的數(shù)據(jù)同步做準(zhǔn)備。