1.java EE 项目的缓存实现
例如:做我在做java NIO 通信项目时有操作数据库的操作,可以给操作数据库的service或者dao层加上数据库缓存
我写个demo 是maven的project 项目结构
1.1 :pom.xml
1.2:ehcache.xml 配置文件
1.3:主要代码
import net.sf.ehcache.*;
public class MyEhcache {
private static String configPath = "/ehcache.xml";// Ehcache 配置文件路径
private static MyEhcache ehcache;
private CacheManager manager;
public MyEhcache(String configPath) {
MyEhcache.configPath = configPath;
manager = CacheManager.create(getClass().getResource(configPath));
}
public static MyEhcache getInstance() {
if (ehcache == null) {
ehcache = new MyEhcache(configPath);
}
return ehcache;
}
/**
* 初始化一个缓存
* @Title: init
* @Description: TODO(这里用一句话描述这个方法的作用)
* @param @param cacheName
* @return void 返回类型
* @throws
*/
public void init(String cacheName){
manager.addCache(cacheName);
}
/**
* @Title: add
* @Description:(想指定缓存名称的缓存添加 缓存的对象)
* @param @param cacheName
* @param @param key
* @param @param value
* @return void 返回类型
* @throws
*/
public void add(String cacheName, String key, Object value) {
Cache cache = manager.getCache(cacheName);
Element element = new Element(key, value);
cache.put(element);
}
/**
* @Title: get
* @Description:(从指定缓存名称的缓存中取出缓存的对象)
* @param @param cacheName
* @param @param key
* @param @return
* @return Object 返回类型
* @throws
*/
public Object get(String cacheName, String key) {
Cache cache = manager.getCache(cacheName);
Element element = cache.get(key);
return element == null ? null : element.getObjectValue();
}
/**
*
* @Title: remove
* @Description: (从指定的缓存中删除缓存的对象)
* @param @param cacheName
* @param @param key
* @return void 返回类型
* @throws
*/
public void remove(String cacheName, String key) {
Cache cache = manager.getCache(cacheName);
cache.remove(key);
}
}
public class App
{
public static void main( String[] args )
{
System.out.println( "测试 ehcache" );
MyEhcache ehcache=MyEhcache.getInstance();
ehcache.init("test");
ehcache.add("test", "printkey", "Hello World!");
if(ehcache.get("test", "printkey")!=null){
System.out.println(ehcache.get("test", "printkey"));
}else{
System.out.println("缓存中没有数据");
}
}
}