2011-05-10 09:38
EhCache在项目中的应用(2)
* 获取指定名称的缓存
* @param cache_name
* 缓存名称,如ehcache.xml中<br>产品实体配置的name:com.handou.ehcache.Product
* @return 包含所有com.handou.ehcache.Product对象的缓存实例
* @throws IllegalStateException
*/
public static Cache getCache(String cache_name)
throws IllegalStateException {
return manager.getCache(cache_name);
}
/**
* 获取缓存中的信息
* @param cache_name
* 缓存名称,如ehcache.xml中
<br>产品实体配置的name:com.handou.ehcache.Product
* @param key
* 缓存对象的主键(具有唯一性的字符串)
* @return key标识的对象
* @throws IllegalStateException
* @throws CacheException
*/
public static Element getElement(String cache_name, Serializable key)
throws IllegalStateException, CacheException {
Cache cache = getCache(cache_name);
return cache.get(key);
}
/**
*删除缓存中的信息
* @param cache_name
* 缓存名称,如ehcache.xml中
<br>产品实体配置的name:com.handou.ehcache.Product
* @param key
* 缓存对象的主键(具有唯一性的字符串)
* @return key标识的对象
* @throws IllegalStateException
* @throws CacheException
*/
public static void removeElement(String cache_name, Serializable key) throws IllegalStateException, CacheException {
Cache cache = getCache(cache_name);
cache.remove(key);
}
c)Service中的缓存处理。
当对缓存中的对象进行数据操作时,如果是查询操作,先查询缓存,如果缓存中存在该实体对象,返回该对象;若不存在,查询数据库,并把该实例对象加入缓存中。
Product p = (Product)AppCacheManager.getObjectCached("com.handou.ehcache.Product", id);
if(null==p){
p = ProductDao.getProduct(id);
if(null != p){ AppCacheManager.putObjectCached("com.handou.ehcache.Product", id, (Serializable)p);
}
}
如果是更新操作,先更新数据库,接着更新缓存中的对象。
ProductDao.updateProduct(p);
AppCacheManager.putObjectCached("com.handou.ehcache.Product", id, (Serializable)p);
如果是删除操作,操作完数据库之后,删除缓存中的对象。
ProductDao.deleteProduct(p);
AppCacheManager.removeElement("com.handou.ehcache.Product", p.getId());
当然,如果你的项目中使用了spring,可用AOP对缓存采取统一管理,简化编程的具体实现。
针对前面提到的,像百度新闻首页的大量数据缓存,EhCache自身提供页面缓存的实现:net.sf.ehcache.constructs.web.filter.SimplePageCachingFilter
假设百度新闻首页的页面名称为indexNews.jsp,则具体配置实现为:
1)在web.xml中配置SimplePageCachingFilter,并拦截请求路径为indexNews.jsp的请求,配置代码如下:
<filter>
<filter-name>SimplePageCachingFilter</filter-name>
<filter-class>
net.sf.ehcache.constructs.web.filter.SimplePageCachingFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>SimplePageCachingFilter</filter-name>
<url-pattern>/indexNews.jsp</url-pattern>
</filter-mapping>
2)在ehcache.xml配置SimplePageCachingFilter的缓存
<cache name="SimplePageCachingFilter"
maxElementsInMemory="1000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
overflowToDisk="true"
/>
通过以上配置,即可完成页面数据的缓存,不用每一次请求都要通过数据库查询大量数据而牺牲系统性能