JAVA缓存最简单一种实现
创建一个静态的map ConcurrentHashMap 线程安全
本地文件缓存
Ehcache 缓存
jar包
ehcache-core-2.5.2.jar slf4j-api-1.6.1.jar slf4j-jdk14-1.6.1.jar
配置 ehcache.xml
可配置多个cache
通过 Cache sample = cacheManager.getCache("name");获取缓存对象
xsi:noNamespaceSchemaLocation="../bin/ehcache.xsd">
JAVA 代码
1.获取CacheManager 对象 不传参数表示默认路径 可以传入文件路径和网络地址
2.CacheManager cacheManager = CacheManager.create();
获取ehcache.xml 文件里配置好的 cache
Cache sample = cacheManager.getCache("SimplePageCachingFilter");
3.创建 缓存元素 key 和 val 字面意思
Element element = new Element("key", "val");
4.sample.put(element); 将缓存对象 加入缓存
通过key获取cache中的 缓存元素
Element result = sample.get("key");
注意添加到cache中对象要序列化 实现Serializable接口
通过 次元素 可获取 val等 属性的值
删除缓存
sample.remove("key");
sample.removeAll();
获取所有的缓存对象
for (Object key : cache.getKeys()) {
System.out.println(key);
}
得到缓存中的对象数
cache.getSize();
得到缓存对象占用内存的大小
cache.getMemoryStoreSize();
得到缓存读取的命中次数
cache.getStatistics().getCacheHits();
得到缓存读取的错失次数
cache.getStatistics().getCacheMisses();
写入磁盘
cache.flush();
要想把cache真正持久化到磁盘,写程序时必须注意,在是用net.sf.ehcache.Cache的void put (Element element)方法后要使用void flush()方法
创建个缓存
Ehcache cache = new Cache("testCache", 5000, false, false, 5, 2);
sample.add(cache )
Ehcache整合MyBatis
导入 mybatis-ehcache-1.0.0.jar 还有其他myBatis相关包
mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
select * fr