ehcache 缓存

1、通过使用API来动态的添加缓存(将缓存的配置信息通过java代码来实现而非写在配置文件)

2、通过配置文件ehcache.xml创建缓存实例

package org.jeecgframework.cache;

import org.jeecgframework.core.util.StringExt;

public class CacheInstance {
    private static ICache cache = new EHCache();
    /**
     * 加入缓存
     * */
    public static boolean setObject(String key, Object value) {
        if (StringExt.isBlank(key)) {
            return false;
        }
        if(null == value){
            cache.removeObject(key);
            return true;
        }
        return cache.setObject(key, value);
    }

    /**
     * 从缓存获取数据
     * */
    public static Object getObject(String key) {
        if (StringExt.isBlank(key)) {
            return null;
        }
        return cache.getObject(key);
    }

    /**
     * 删除缓存数据
     * */
    public static boolean removeObject(String key) {
        if (StringExt.isBlank(key)) {
            return false;
        }
        return cache.removeObject(key);
    }
}

package org.jeecgframework.cache;

import org.ehcache.Cache;
import org.ehcache.CacheManager;
import org.ehcache.config.builders.CacheConfigurationBuilder;
import org.ehcache.config.builders.CacheManagerBuilder;
import org.ehcache.config.builders.ResourcePoolsBuilder;
import java.util.*;

public class EHCache implements ICache {
    private static Cache<String, Object> objectCache;

    private Cache<String, Object> getObjectCache() {
        if (null == objectCache) {
            CacheManager cacheManager = CacheManagerBuilder
                    .newCacheManagerBuilder()
                    .withCache(
                            "obj",
                            CacheConfigurationBuilder.newCacheConfigurationBuilder(
                                    String.class, Object.class,
                                    ResourcePoolsBuilder.heap(200)).build())
                    .build(true);
            objectCache = cacheManager.getCache("obj", String.class, Object.class);

        }
        return objectCache;
    }

    public boolean setObject(String key, Object value) {
        getObjectCache().put(key, value);
        return true;
    }

    public Object getObject(String key) {
        return getObjectCache().get(key);
    }

    public boolean removeObject(String key) {
        getObjectCache().remove(key);
        return true;
    }
}
 
 
 

猜你喜欢

转载自www.cnblogs.com/Eeexiang/p/8946386.html