All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.rt.web.util.cache.EhCache Maven / Gradle / Ivy

The newest version!
package com.rt.web.util.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 com.json.JSONArray;
import com.json.JSONObject;

import java.io.Serializable;

/**
 * EhCache
 */
public class EhCache implements CacheFace {

    /**
     * 缓存名
     */
    private static final String NAME = "ehcache";

    private static CacheManager manager = CacheManagerBuilder
            .newCacheManagerBuilder()
            .withCache(
                    NAME,
                    CacheConfigurationBuilder.newCacheConfigurationBuilder(
                            String.class, Serializable.class,
                            ResourcePoolsBuilder.heap(100)).build())
            .build(true);

    private Cache getCache() {
        Cache cache = manager.getCache(NAME, String.class, Serializable.class);
        if (cache == null) {
            cache = manager.createCache(
                    NAME,
                    CacheConfigurationBuilder.newCacheConfigurationBuilder(
                            String.class, Serializable.class,
                            ResourcePoolsBuilder.heap(100)).build());
        }
        return cache;
    }

    /**
     * cache中增加新缓存对象
     *
     * @param key   key
     * @param value value
     */
    @Override
    public void put(String key, Serializable value) {
        getCache().put(key, value.toString());
    }

    /**
     * cache中增加新缓存对象
     *
     * @param key         key
     * @param value       value
     * @param millisDelay millisDelay
     */
    @Override
    public void put(String key, Serializable value, long millisDelay) {
        getCache().put(key, value.toString());
    }

    /**
     * 获取缓存对象
     *
     * @param key key
     * @return Object
     */
    @Override
    public  T get(String key) {
        Serializable item = getCache().get(key);
        if (item instanceof JSONObject) {
            return (T) ((JSONObject) item).copy();
        } else if (item instanceof JSONArray) {
            return (T) ((JSONArray) item).copy();
        }
        return (T) item;
    }

    /**
     * cache是否已存在
     *
     * @param key key
     * @return boolean
     */
    @Override
    public boolean has(String key) {
        return get(key) != null;
    }

    /**
     * cache是否已存在
     *
     * @param key key
     */
    @Override
    public void del(String key) {
        Cache cache = getCache();
        if (cache != null) {
            cache.remove(key);
        }
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy