ehcache cache

1. Dynamically add cache by using API (implement the cached configuration information through java code instead of writing it in the configuration file)

2. Create a cache instance through the configuration file ehcache.xml

 

 

package org.jeecgframework.cache;

import org.jeecgframework.core.util.StringExt;

public  class CacheInstance {
     private  static ICache cache = new EHCache ();
    / **
     * add cache
     * */
    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);
    }

    /**
     * Get data from cache
     * */
    public static Object getObject(String key) {
        if (StringExt.isBlank(key)) {
            return null;
        }
        return cache.getObject(key);
    }

    /**
     * delete cached data
     * */
    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;
    }
}
 
 
 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324854458&siteId=291194637