一直以来懒得配置缓存,基本的缓存也就是orm层,基本上都交给hibernate去配置了。这段时间,感觉页面速度太慢了,还是需要使用缓存。现在的缓存工具也挺多的,较不错的属ehcache和oscache了。决定分别研究一下。
先来说说ehcache,目前的版本为1.2,已经支持集群了。对于ehcache的使用,感觉很容易上手,基本上都是配置。以前在hibernate的时候配置过,所以也不是很陌生。API也挺简单,如下的api:
CacheManager主要的缓存管理类,一般一个应用为一个实例,如下
CacheManager.create();也可以使用new CacheManager的方式创建
默认的配置文件为ehcache.xml文件,也可以使用不同的配置:
java 代码
- CacheManager manager = new CacheManager("src/config/other.xml");
缓存的创建,采用自动的方式
java 代码
- CacheManager singletonManager = CacheManager.create();
- singletonManager.addCache("testCache");
- Cache test = singletonManager.getCache("testCache");
或者直接创建Cache
java 代码
- CacheManager singletonManager = CacheManager.create();
- Cache memoryOnlyCache = new Cache("testCache", 5000, false, false, 5, 2);
- manager.addCache(memoryOnlyCache);
- Cache test = singletonManager.getCache("testCache");
删除cache
java 代码
- CacheManager singletonManager = CacheManager.create();
- singletonManager.removeCache("sampleCache1");
在使用ehcache后,需要关闭
java 代码
- CacheManager.getInstance().shutdown()
- caches 的使用
- Cache cache = manager.getCache("sampleCache1");
执行crud操作
java 代码
- Cache cache = manager.getCache("sampleCache1");
- Element element = new Element("key1", "value1");
- cache.put(element);
- update
- Cache cache = manager.getCache("sampleCache1");
- cache.put(new Element("key1", "value1");
- //This updates the entry for "key1"
- cache.put(new Element("key1", "value2");
- get Serializable
- Cache cache = manager.getCache("sampleCache1");
- Element element = cache.get("key1");
- Serializable value = element.getValue();
- get non serializable
- Cache cache = manager.getCache("sampleCache1");
- Element element = cache.get("key1");
- Object value = element.getObjectValue();
- remove
- Cache cache = manager.getCache("sampleCache1");
- Element element = new Element("key1", "value1"
- cache.remove("key1");
不过缓存还是基本上以配置方式为主,下一篇文章将会说明ehcache如何配置