EhCache缓存框架(4)-使用单列模式封装Ehcache常用方法

xiaoxiao2021-02-28  11

简单粗暴,直接贴代码

Ehcache工具类:

package com.spf.common.utils; import net.sf.ehcache.Cache; import net.sf.ehcache.CacheManager; import net.sf.ehcache.Element; /** * EhCache 缓存框架 * @Auther SPF * @Create 2017/8/20 */ public class EhCacheUtil { private static EhCacheUtil cacheUtil = null; private static Cache cache = null; private static CacheManager manager = null; public EhCacheUtil(String url,String str){ manager = CacheManager.create(url); cache = manager.getCache(str); } public static EhCacheUtil getInstance(String url,String str){ if (cacheUtil == null) { cacheUtil = new EhCacheUtil(url,str); } return cacheUtil; } /** * 向 Ehcache 中添加数据 * @param key key值 * @param obj value值 */ public void put(String key,Object obj) throws Exception { put(key,obj,false); } /** * 不覆盖添加数据时是如果key值存在则抛出异常 * @param key key值 * @param obj value值 * @param isCover 是否覆盖添加数据 */ public void put(String key,Object obj,boolean isCover) throws Exception { if (isCover == true) { if (isExist(key)) { throw new Exception("Ehcache中该key值数已存在"); } } Element element = new Element(key,obj); cache.put(element); cache.flush(); } /** * 从 Ehcache 根据key值获取数据 * @param key key值 * @return obj */ public Object get(String key) { Object obj = null; try { obj = cache.get(key).getObjectValue(); }catch (NullPointerException e) { throw new NullPointerException("Ehcache中不存在该值的数据!"); } finally { manager.shutdown(); } return obj; } /** * 从 Ehcache 根据key值删除数据 * @param key */ public boolean remove(String key) { boolean flag = cache.remove(key); cache.flush(); return flag; } /** * 根据key值判断是否存在 * @param key key值 * @return boolean值 */ public boolean isExist(String key){ if (cache.get(key) != null) { return true; } return false; } public void close(){ manager.shutdown(); } }

测试类:

public class EhCacheTest { public static void main(String[] args) { EhCacheUtil cacheUtil = EhCacheUtil.getInstance("./dubbo-common/src/main/resources/ehcache.xml","a"); try { cacheUtil.put("sf","Ehcache测试数据一",true); } catch (Exception e) { e.printStackTrace(); } //Object s = cacheUtil.get("sf"); //System.out.println(s); //boolean flag = cacheUtil.remove("sf"); //System.out.println(flag); // System.out.println(s); cacheUtil.close(); } }

转载请注明原文地址: https://www.6miu.com/read-750204.html

最新回复(0)