Nemo

Nemo 关注TA

路漫漫其修远兮,吾将上下而求索。

Nemo

Nemo

关注TA

路漫漫其修远兮,吾将上下而求索。

  •  普罗旺斯
  • 负责帅就完事了
  • 写了1,496,113字

该文章投稿至Nemo社区   Java  板块 复制链接


CacheUtils

发布于 2016/08/18 16:20 3,252浏览 0回复 4,129


package com.nemo.utils;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;

/**
 * Cache工具类
 * @author Nemo
 */
public class CacheUtils {

        private static CacheManager cacheManager = ((CacheManager)SpringContextHolder.getBean("cacheManager"));

        private static final String SYS_CACHE = "sysCache";

        public static Object get(String key) {
                return get(SYS_CACHE, key);
        }

        public static void put(String key, Object value) {
                put(SYS_CACHE, key, value);
        }

        public static void remove(String key) {
                remove(SYS_CACHE, key);
        }
        
        public static Object get(String cacheName, String key) {
                Element element = getCache(cacheName).get(key);
                return element==null?null:element.getObjectValue();
        }

        public static void put(String cacheName, String key, Object value) {
                Element element = new Element(key, value);
                getCache(cacheName).put(element);
        }

        public static void remove(String cacheName, String key) {
                getCache(cacheName).remove(key);
        }
        
        /**
         * 获得一个Cache,没有则创建一个。
         * @param cacheName
         * @return
         */
        private static Cache getCache(String cacheName){
                Cache cache = cacheManager.getCache(cacheName);
                if (cache == null){
                        cacheManager.addCache(cacheName);
                        cache = cacheManager.getCache(cacheName);
                        cache.getCacheConfiguration().setEternal(true);
                }
                return cache;
        }

        public static CacheManager getCacheManager() {
                return cacheManager;
        }

}


本文标签
 {{tag}}
点了个评