Ehcache学习1:JDBC caching

Ehcache学习一:JDBC caching

Ehcache很容易加入到已经使用的JDBC代码中,一般在两种情况下使用Ehcache:

 1、通过ID获取一个实体
 2、一些可以接受不一致性的查询。

 

其使用方式非常简单:

	public ProductInfo selOneProduct(String id) throws SQLException {
		// 先在cache中查找相关信息
		ProductInfo productinfo=null;
		String cacheName = "BYSJProductInfo";
		//第一步:以单例的方式创建CacheManager,默认调用JAR包中的ehcache-failsafe.xml配置文件
		CacheManager cacheManager = CacheManager.create();
		//第二步:根据cache名称获取Ehcache,如果在ehcache-failsafe.xml已经配置这个名称的Ehcache,则可以获取到,
		//如果没有配置,也可以new一个Ehcache,当然一般在代码中是通过配置的方式写的。
		Ehcache cache = cacheManager.getEhcache(cacheName);
		if (cache == null) {
			cache = new Cache(cacheName, 100, true, false, 120, 120);
			cacheManager.addCache(cache);
		}
 /*
		 * 第三步:根据key获取Ehcache中的存储的Element.
		 * 第四步:通过Element得到你要的value.
		 * element.getValue():只有productinfo对象实现了串行化接口才可以使用getValue(),一般都使用getObjectValue()
		*/

		Element element = cache.get(id);
				if (element != null) {
			productinfo = (ProductInfo) element.getObjectValue();
		}
		if (productinfo == null) {
			System.out.println("从数据库中查找");
                                               ..........
// 取商品信息结束
			if (productinfo != null) {
				cache.put(new Element(id, productinfo));
			}
		}
		return productinfo;

	}

上面这个例子是最plain的一个例子,在项目中是不会这样写的,但是最简单的越容易理解。

我们可以看到,Ehcache分三级来管理,CacheManager -->Ehcache-->Element

CacheManager 可以使用单例模式来构建,也可以new.

Ehcache 是在配置文件中可以配置,有一个name来唯一标识。

Element:存储一条条实际的数据。