ehcache 使用简例

import com.google.common.base.Function;

import net.sf.ehcache.Cache;

/**
 * <pre>
 * Test.java
 * @author kanpiaoxue<br>
 * @version 1.0
 * Create Time 2014年9月15日 上午10:04:06<br>
 * Description :
 * </pre>
 */
public class Test {

    /**
     * <pre>
     * @param args
     * </pre>
     */
    public static void main(String[] args) {
        Test test = new Test();
        test.testCache();
        test.testCache1();

    }

    // private CacheService cacheService = new CacheServiceImpl();
    private final CacheService cacheService = new CacheServiceImpl(
            "../ehcache.xml");

    public void testCache() {

        final String key = "kanpiaoxue";
        int count = 100;
        Cache cache = cacheService.getCacheManager().getCache(
                "org.kanpiaoxue.learn.ecache.test01");

        for (int i = 0; i < count; i++) {
            Person one = cacheService.getObjectWithKey(key,
                    new Function<String, Person>() {

                        @Override
                        public Person apply(String input) {
                            return null;// new Person(key, key, 33);
                        }
                    }, cache);

            System.out.println(one);
            Person one1 = cacheService.getObjectWithKey(key,
                    new Function<String, Person>() {

                        @Override
                        public Person apply(String input) {
                            return null;// new Person(key, key, 33);
                        }
                    }, cache);

            System.out.println(one1);
        }

        System.out.println(String.format("java.io.tmpdir:%s",
                System.getProperty("java.io.tmpdir")));
    }
    public void testCache1() {
        
        final String key = "kanpiaoxue";
        int count = 100;
        Cache cache = cacheService.getCacheManager().getCache(
                "org.kanpiaoxue.learn.ecache.test01");
        
        for (int i = 0; i < count; i++) {
            Person one = cacheService.getObjectWithKey(key,
                    new Function<String, Person>() {
                
                @Override
                public Person apply(String input) {
                    return null;// new Person(key, key, 33);
                }
            }, cache);
            
            System.out.println(one);
            Person one1 = cacheService.getObjectWithKey(key,
                    new Function<String, Person>() {
                
                @Override
                public Person apply(String input) {
                    return null;// new Person(key, key, 33);
                }
            }, cache);
            
            System.out.println(one1);
        }
        
        System.out.println(String.format("java.io.tmpdir:%s",
                System.getProperty("java.io.tmpdir")));
    }
import com.google.common.base.Function;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;

/**
 * <pre>
 * CacheService.java
 * @author kanpiaoxue<br>
 * @version 1.0
 * Create Time 2014年9月15日 上午11:09:47<br>
 * Description : cache缓存的服务接口
 * </pre>
 */
public interface CacheService {

    /**
     * <pre>
     * @param cacheName cache的名称
     * @param key 取值的key
     * @param function 生成key值的函数
     * @return
     * </pre>
     */
    public abstract <F, T> T getObjectWithKey(String cacheName, F key,
            Function<F, T> function);

    /**
     * <pre>
     * @param key 取值的key
     * @param function 生成key值的函数
     * @param cache cache实例
     * @return
     * </pre>
     */
    public abstract <F, T> T getObjectWithKey(F key, Function<F, T> function,
            Cache cache);

    /**
     * <pre>
     * @return CacheManager
     * </pre>
     */
    public abstract CacheManager getCacheManager();

}
 
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.base.Function;
import com.google.common.base.Preconditions;
import com.google.common.base.Stopwatch;
import com.google.common.base.Strings;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;

import java.io.File;

/**
 * <pre>
 * CacheUtils.java
 * @author kanpiaoxue<br>
 * @version 1.0
 * Create Time 2014年9月15日 上午10:19:32<br>
 * Description : ehcache缓存实现类
 * </pre>
 */
public class CacheServiceImpl implements CacheService {
    private final CacheManager cacheManager;

    private final Logger LOGGER = LoggerFactory
            .getLogger(CacheServiceImpl.class);

    /**
     * <pre>
     * ehcache.xml 在 classpath 里面
     * </pre>
     */
    public CacheServiceImpl() {
        super();
        this.cacheManager = new CacheManager();
    }

    /**
     * <pre>
     * @param configFile ehcache.xml 的配置文件绝对路径
     * </pre>
     */
    public CacheServiceImpl(String configFile) {
        super();
        Preconditions.checkArgument(new File(configFile).isFile(),
                "configFile is not a valid file!");
        this.cacheManager = new CacheManager(configFile);
    }


    @Override
    public CacheManager getCacheManager() {
        return cacheManager;
    }


    @Override
    public <F, T> T getObjectWithKey(F key, Function<F, T> function, Cache cache) {
        Preconditions.checkNotNull(cache, "cache is null!");
        Preconditions.checkNotNull(key, "key is null!");
        Preconditions.checkNotNull(function, "function is null!");
        Stopwatch watch = null;
        if (LOGGER.isDebugEnabled()) {
            watch = Stopwatch.createStarted();
        }
        Element element;
        if ((element = cache.get(key)) != null) {
            @SuppressWarnings("unchecked")
            T t = ((T) element.getObjectValue());
            LOGGER.debug(String.format("get %s from cache, It consumes %s.", t,
                    watch));
            return t;
        } else {
            Object value = null;
            if ((value = function.apply(key)) != null) {
                element = new Element(key, value);
                cache.put(element);
            }
            @SuppressWarnings("unchecked")
            T t = (T) value;
            LOGGER.debug(String.format("get %s from original, It consumes %s.",
                    value, watch));
            return t;
        }
    }


    @Override
    public <F, T> T getObjectWithKey(String cacheName, F key,
            Function<F, T> function) {
        Preconditions.checkArgument(!Strings.isNullOrEmpty(cacheName),
                "cacheName is null or empty!");
        Cache cache = cacheManager.getCache(cacheName);
        return getObjectWithKey(key, function, cache);
    }

}
 

ehcache.xml
<?xml version="1.0" encoding="UTF-8"?>
<ehcache name="kanpiaoxue.cache" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="ehcache.xsd"
         updateCheck="true" monitoring="autodetect"
         dynamicConfig="true">

  <diskStore path="java.io.tmpdir"/>
  <defaultCache
      maxEntriesLocalHeap="10000"
      maxEntriesLocalDisk="1000000"
      diskSpoolBufferSizeMB="200"
      eternal="false"
      timeToIdleSeconds="1200"
      timeToLiveSeconds="1200"
      overflowToDisk="true"
      diskPersistent="false"
      diskExpiryThreadIntervalSeconds="120"
      memoryStoreEvictionPolicy="LRU"/>

    <cache name="org.kanpiaoxue.learn.ecache.test01"
           maxEntriesLocalHeap="100000"
           maxEntriesLocalDisk="10000000"
           eternal="false"
           timeToIdleSeconds="60"
           timeToLiveSeconds="60"
           memoryStoreEvictionPolicy="LRU"
           transactionalMode="off">
        <persistence strategy="localTempSwap"/>
    </cache>

</ehcache>
  }

 

 

 

import java.io.Serializable;

/**
 * <pre>
 * Person.java
 * @author kanpiaoxue<br>
 * @version 1.0
 * Create Time 2014年9月15日 上午10:09:03<br>
 * Description :
 * </pre>
 */
public class Person implements Serializable {
    private static final long serialVersionUID = 8585874398117257001L;

    /**
     * <pre>
     * @return the serialversionuid
     * </pre>
     */
    public static long getSerialversionuid() {
        return serialVersionUID;
    }

    private String id;
    private String name;

    private int age;

    /**
     * <pre>
     * </pre>
     */
    public Person() {
        super();
    }

    /**
     * <pre>
     * @param id
     * @param name
     * @param age
     * </pre>
     */
    public Person(String id, String name, int age) {
        super();
        this.id = id;
        this.name = name;
        this.age = age;
    }

    /*
     * (non-Javadoc)
     * @see java.lang.Object#equals(java.lang.Object)
     */
    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        Person other = (Person) obj;
        if (age != other.age) {
            return false;
        }
        if (id == null) {
            if (other.id != null) {
                return false;
            }
        } else if (!id.equals(other.id)) {
            return false;
        }
        if (name == null) {
            if (other.name != null) {
                return false;
            }
        } else if (!name.equals(other.name)) {
            return false;
        }
        return true;
    }

    /**
     * <pre>
     * @return the age
     * </pre>
     */
    public int getAge() {
        return age;
    }

    /**
     * <pre>
     * @return the id
     * </pre>
     */
    public String getId() {
        return id;
    }

    /**
     * <pre>
     * @return the name
     * </pre>
     */
    public String getName() {
        return name;
    }

    /*
     * (non-Javadoc)
     * @see java.lang.Object#hashCode()
     */
    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + age;
        result = prime * result + ((id == null) ? 0 : id.hashCode());
        result = prime * result + ((name == null) ? 0 : name.hashCode());
        return result;
    }

    /**
     * <pre>
     * @param age the age to set
     * </pre>
     */
    public void setAge(int age) {
        this.age = age;
    }

    /**
     * <pre>
     * @param id the id to set
     * </pre>
     */
    public void setId(String id) {
        this.id = id;
    }

    /**
     * <pre>
     * @param name the name to set
     * </pre>
     */
    public void setName(String name) {
        this.name = name;
    }

    /*
     * (non-Javadoc)
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        return "Person [id=" + id + ", name=" + name + ", age=" + age + "]";
    }

}

 

参考: 

http://blog.csdn.net/mgoann/article/details/4095155

http://blog.csdn.net/mgoann/article/details/4099190

http://www.ehcache.org/

 

猜你喜欢

转载自kanpiaoxue.iteye.com/blog/2116568
今日推荐