spring ehcache 内存管理

本文介绍了一种使用Spring框架整合EHCache缓存管理器的方法。通过实现自定义EhcacheManager类来操作缓存,包括增删查改等基本功能,并记录了异常处理流程。

spring 整合了ehcache,包名 spring-context-support

spirng 类 EhCacheCacheManager  引用了 ehcache 中 CacheManager 类,以达到内存的目的

 

代码 

public class EhcacheManager implements CacheManager {

    private Logger log = Logger.getLogger(this.getClass());

    private EhCacheCacheManager springEhcacheManager;

    private String cacheName;

    @Override
    public void put(String key, Object value, int timeToLive) {
        try {
            getCache().put(key, value);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

    @Override
    public boolean add(String key, Object value, int timeToLive) {
        try {
            getCache().put(key, value);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }

        return true;
    }

    @Override
    public Object get(String key) {
        try {
            Cache.ValueWrapper value = getCache().get(key);
            if (value == null) {
                return null;
            }
            return getCache().get(key).get();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return null;
        }

    }

    @Override
    public Object getAndTouch(String key, int timeToLive) {
        return get(key);
    }

    @Override
    public void delete(String key) {
        try {
            getCache().evict(key);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

    @Override
    public boolean containsKey(String key) {
        try {
            Cache.ValueWrapper value = getCache().get(key);
            return value != null;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return false;
        }

    }

    public EhCacheCacheManager getSpringEhcacheManager() {
        return springEhcacheManager;
    }

    public void setSpringEhcacheManager(EhCacheCacheManager springEhcacheManager) {
        this.springEhcacheManager = springEhcacheManager;
    }

    public String getCacheName() {
        return cacheName;
    }

    public void setCacheName(String cacheName) {
        this.cacheName = cacheName;
    }

    private Cache getCache(){
        return springEhcacheManager.getCache(cacheName);
    }
}
 

转载于:https://my.oschina.net/u/198077/blog/1593828

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值