EhCacheUtil.java 1.28 KB
package com.subsidy.util;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
import org.springframework.util.ClassUtils;

/**
 * <p>
 *  Ehcache
 * </p>
 *
 * @author DengMin
 * @since 2022/8/1
 */
public class EhCacheUtil {

    static CacheManager cacheManager = CacheManager.newInstance(ClassUtils.getDefaultClassLoader().getResource("").getPath()+"ehcache.xml");

    /**
     * 添加缓存
     * @param cacheName
     * @param key
     * @param value
     */
    public static void putEhCache(String cacheName, String key, Object value) {
        Cache cache = cacheManager.getCache(cacheName);
        Element element = new Element(key, value);
        cache.put(element);
    }

    /**
     * 获取缓存数据
     * @param cacheName
     * @param key
     * @return
     */
    public static Object getEhCache(String cacheName, String key) {
        Cache cache = cacheManager.getCache(cacheName);
        Element element = cache.get(key);
        return element == null ? null : element.getObjectValue();
    }

    /**
     * 删除缓存
     * @param cacheName
     * @param key
     */
    public static void deleteEhCache(String cacheName, String key) {
        Cache cache = cacheManager.getCache(cacheName);
        cache.remove(key);
    }
}