前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >EhCache缓存工具类 原

EhCache缓存工具类 原

作者头像
wuweixiang
发布2018-08-14 14:51:49
9850
发布2018-08-14 14:51:49
举报
文章被收录于专栏:吴伟祥吴伟祥

参考:https://blog.csdn.net/qq_34531925/article/details/79134903

缓存注解使用参考:https://www.cnblogs.com/coprince/p/5984816.html

                                https://www.cnblogs.com/coprince/p/5984816.html

代码语言:javascript
复制
import net.sf.ehcache.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.Serializable;
import java.util.Collection;

/**
 * EhCacheUtil
 * <p>
 * 使用说明:
 * 1、
 * 在需要缓存的 DAO的 *mapper.xml中添加
 * 以下两个<cache>标签都可以,第一个可以输出日志,第二个不输出日志
 * <cache type="org.mybatis.caches.ehcache.LoggingEhcache"/>
 * <cache type="org.mybatis.caches.ehcache.EhcacheCache"/>
 * 也可在单条中配置 :flushCache    useCache 的属性
 * 2、
 * 首先在ehcache.xml中配置缓存策略,即添加一组cache。
 * 参考下方代码
 * 3、注解
 *
 * @author weixiang.wu
 * @CachePut 应用到写数据的方法上,如新增/修改方法,调用方法时会自动把相应的数据放入缓存
 * @CacheEvict 即应用到移除数据的方法上,如删除方法,调用方法时会从缓存中移除相应的数据
 * @Cacheable 应用到读取数据的方法上,即可缓存的方法,如查找方法:先从缓存中读取,如果没有再调用方法获取数据,然后把数据添加到缓存中
 * 可见:https://blog.csdn.net/whatlookingfor/article/details/51833378
 * @date 2018 -04-02 20:09
 */
public class EhCacheUtil {

    private final static Logger logger = LoggerFactory.getLogger(EhCacheUtil.class);

    static CacheManager manager = null;

    static {
        try {
            manager = CacheManager.create(EhCacheUtil.class.getClassLoader().getResourceAsStream("ehcache.xml"));
        } catch (CacheException e) {
            logger.error("获取ehcache.xml失败", e.getMessage());
        }
    }

    /**
     * 存入
     *
     * @param <T>       the type parameter
     * @param cacheName the cache name
     * @param key       键
     * @param value     值
     */
    public static <T extends Serializable> void put(String cacheName, String key, T value) {
        Cache cache = checkCache(cacheName);
        Element e = new Element(key, value);
        cache.put(e);
        cache.flush();
    }

    /**
     * 存入 并设置元素是否永恒保存
     *
     * @param <T>       the type parameter
     * @param cacheName the cache name
     * @param key       键
     * @param value     值
     * @param eternal   对象是否永久有效,一但设置了,timeout将不起作用
     */
    public static <T extends Serializable> void put(String cacheName, String key, T value, boolean eternal) {
        Cache cache = checkCache(cacheName);
        Element element = new Element(key, value);
        element.setEternal(eternal);
        cache.put(element);
        cache.flush();
    }

    /**
     * 存入
     *
     * @param <T>               the type parameter
     * @param cacheName         the cache name
     * @param key               键
     * @param value             值
     * @param timeToLiveSeconds 最大存活时间
     * @param timeToIdleSeconds 最大访问间隔时间
     */
    public static <T extends Serializable> void put(String cacheName, String key, T value, int timeToLiveSeconds, int timeToIdleSeconds) {
        Cache cache = checkCache(cacheName);
        Element element = new Element(key, value);
        element.setTimeToLive(timeToLiveSeconds);
        element.setTimeToIdle(timeToIdleSeconds);
        cache.put(element);
        cache.flush();
    }

    /**
     * Get object.
     *
     * @param cacheName the cache name
     * @param key       the key
     * @return the object
     */
    public static Object get(String cacheName, String key) {
        Cache cache = checkCache(cacheName);
        Element e = cache.get(key);
        if (e != null) {
            return e.getObjectValue();
        }
        return null;
    }

    /**
     * Remove.
     *
     * @param cacheName the cache name
     * @param key       the key
     */
    public static void remove(String cacheName, String key) {
        Cache cache = checkCache(cacheName);
        cache.remove(key);
    }

    /**
     * Remove all.
     *
     * @param cacheName the cache name
     * @param keys      the keys
     */
    public static void removeAll(String cacheName, Collection<String> keys) {
        Cache cache = checkCache(cacheName);
        cache.removeAll(keys);
    }

  /**
     * Clears the contents of all caches in the CacheManager, but without
     * removing any caches.
     * <p/>
     * This method is not synchronized. It only guarantees to clear those elements in a cache at 
     * the time that the
     * {@link Ehcache#removeAll()} mehod on each cache is called.
     */
    public static void clearAll() {
        manager.clearAll();
    }

    private static Cache checkCache(String cacheName) {
        Cache cache = manager.getCache(cacheName);
        if (null == cache) {
            throw new IllegalArgumentException("name=["+cacheName+"],不存在对应的缓存组,请查看ehcache.xml");
        }
        return cache;
    }

}
代码语言:javascript
复制
   public static void main(String[] args) {
        // Create a cache manager
        final CacheManager cacheManager = new CacheManager();

        // create the cache called "helloworld"
        final Cache cache = cacheManager.getCache("helloworld");

        // create a key to map the data to
        final String key = "greeting";

        // Create a data element
        final Element putGreeting = new Element(key, "Hello, World!");

        // Put the element into the data store
        cache.put(putGreeting);

        // Retrieve the data element
        final Element getGreeting = cache.get(key);

        // Print the value
        logger.info(String.valueOf(getGreeting.getObjectValue()));
    }
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档