在看hibernate的官方文档时,看到关于缓存的介绍。
hibernate在缓存管理上做的很好,具体使用,本章不做讲解,本篇主要研究EhCache的用法。其中hibernate使用到的缓存提供商列表如下:
Cache | Provider class | Type | Cluster Safe | Query Cache Supported |
---|---|---|---|---|
Hashtable (not intended for production use) | org.hibernate.cache.HashtableCacheProvider |
memory | yes | |
EHCache | org.hibernate.cache.EhCacheProvider |
memory, disk, transactional, clustered | yes | yes |
OSCache | org.hibernate.cache.OSCacheProvider |
memory,disk | yes | |
SwarmCache | org.hibernate.cache.SwarmCacheProvider |
clustered (ip multicast) | yes (clustered invalidation) | |
JBoss Cache 1.x | org.hibernate.cache.TreeCacheProvider |
clustered (ip multicast), transactional | yes (replication) | yes (clock sync req.) |
JBoss Cache 2 | org.hibernate.cache.jbc.JBossCacheRegionFactory |
clustered (ip multicast), transactional | yes (replication or invalidation) | yes (clock sync req.) |
其中,我对EHCache比较感兴趣。看它支持的类型包括对内存,硬盘,传统,集群都支持。
我们可以单独研究一下Ehcache缓存的使用,这样方便以后我们对其他使用到缓存的地方进行缓存的自定义管理(不单单在hibernate查询数据方面)。
ehcache下载地址: http://sourceforge.net/projects/ehcache/files/ehcache/
先写个例子,看看它的api如何使用:
EhcacheTest
package org.base.cache.test;
import java.net.MalformedURLException;
import java.net.URL;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
import net.sf.ehcache.config.CacheConfiguration;
import net.sf.ehcache.config.Configuration;
/**
* Ehcache缓存管理的api测试小例子
* @author lushuaiyin
*
*/
public class EhcacheTest {
/**
* @param args
*/
public static void main(String[] args) throws MalformedURLException {
net.sf.ehcache.config.Configuration config=new Configuration();
//如果不使用ehcache.xml配置文件,那么必须用代码配置一个defaultCacheConfiguration
CacheConfiguration defaultCacheConfiguration=new CacheConfiguration();
defaultCacheConfiguration.setMaxEntriesLocalHeap(0);
defaultCacheConfiguration.setEternal(false);
defaultCacheConfiguration.setTimeToIdleSeconds(30);
defaultCacheConfiguration.setTimeToLiveSeconds(30);
config.addDefaultCache(defaultCacheConfiguration);//设置默认cache
net.sf.ehcache.CacheManager cacheManager=CacheManager.create(config);
//创建缓存信息
/*构造方法有多种,详见文档
public Cache(String name,
int maxElementsInMemory,
boolean overflowToDisk,
boolean eternal,
long timeToLiveSeconds,
long timeToIdleSeconds)
*/
//自定义配置缓存
net.sf.ehcache.Cache cache1=new Cache("mycache-one", 1000