Ecache用法1

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("缓存中没有数据");

        }        

    }

}



  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值