分享

Ehcache 缓存组件

 Bladexu的文库 2017-10-24

Ehcache介绍

ehcache是一个非常轻量级的缓存实现,ehcache 是一个纯Java的进程内缓存框架特别高效。


Ehcache学习使用

使用ehcache最核心的一点就在于其ehcache.xml配置文件。
ehcache.xml

<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www./2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="ehcache.xsd" updateCheck="false"
monitoring="autodetect" dynamicConfig="false" name="talent-default-ehcache">

    <diskStore path="D:/cache/ehcache.txt" />
    <!-- Mandatory Default Cache configuration. These settings will be applied 
        to caches created programmtically using CacheManager.add(String cacheName). 
        通常保留defaultCache的配置 The defaultCache has an implicit name "default" which 
        is a reserved cache name. -->
    <defaultCache maxElementsInMemory="1000000" eternal="false"
        timeToIdleSeconds="1200" timeToLiveSeconds="1200" overflowToDisk="true"
        diskSpoolBufferSizeMB="30" maxElementsOnDisk="10000000"
        diskPersistent="false" diskExpiryThreadIntervalSeconds="120"
        memoryStoreEvictionPolicy="LRU" />

    <!-- 定义缓存对象-->
    <!-- 商品品牌缓存 根据品牌id查询品牌name -->
    <cache name="goodsBrand" maxElementsInMemory="200" eternal="false"
        overflowToDisk="true" diskSpoolBufferSizeMB="200" timeToIdleSeconds="7200"
        timeToLiveSeconds="7200" memoryStoreEvictionPolicy="LRU">
    </cache>

    <!-- 城市名 根据城市站id查询城市name -->
    <cache name="cityName" maxElementsInMemory="2000" eternal="false"
        overflowToDisk="true" diskSpoolBufferSizeMB="200" timeToIdleSeconds="7200"
        timeToLiveSeconds="7200" memoryStoreEvictionPolicy="LRU">
    </cache>
</ehcache>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30

缓存对象清除策略:

1、FIFO:first in first out,先进先出策略(不推荐使用)
2、LFU:Less Frequently Used,最少使用原则(清除最少使用的元素对象)缓存的元素有一个hit 属性,hit 值最小的将会被清出缓存。
3、LRU:Least Recently Used,最近最少使用原则,缓存的元素有一个时间戳,当缓存容量满了,而又需要腾出地方来缓存新的元素的时候,那么现有缓存元素中时间戳离当前时间最远的元素将被清出缓存。


1、创建EhcacheManage对象

1)使用默认配置文件(类路径下的ehcache.xml)

CacheManager manager = CacheManager.create();
  • 1
  • 2

2)使用指定的配置文件

CacheManager cacheManager = CacheManager.create(String configurationFileName);
  • 1
  • 2

3)使用输入流方式

CacheManager cacheManager = CacheManager.create(InputStream inputStream);
  • 1
  • 2

主要有两种方式,使用任何一种方式都可以。


2、创建Cache对象

1)获得配置文件中事先已经配置好的Cache缓存对象

Cache cache=cacheManager.getCache(String name);
  • 1
  • 2

2)新建一个Cache并添加到CacheManager里

Cache cache=new Cache(String name,
                 int maxElementsInMemory,
                 MemoryStoreEvictionPolicy memoryStoreEvictionPolicy,
                 boolean overflowToDisk,
                 String diskStorePath,
                 boolean eternal,
                 long timeToLiveSeconds,
                 long timeToIdleSeconds,
                 boolean diskPersistent,
                 long diskExpiryThreadIntervalSeconds,
                 RegisteredEventListeners registeredEventListeners);

一大推相关的配置,推荐在cache.xml配置文件里面配置Cache对象,以便缓存对象管理。 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

3、使用Cache缓存对象

1)添加元素

cache.put(Element element);
Element类似java中的Entry对象,可以去看看Element的源码结构。
  • 1
  • 2
  • 3

2)获取元素

Element element=cache.get(Object key);
  • 1
  • 2

3)删除元素

boolean flag=cache.remove(Object key);
  • 1
  • 2

自定义的工具类(EhCacheUtil)

/**
 * EhCache工具类,主要包含取元素和插入元素。
 * @author xuyi
 *
 */
public class EhCacheUtil {
        private static CacheManager cacheManager;
        private EhCacheUtil() {
        //私有化构造方法
        }

        //静态代码块,保证singleton。
        static {
        cacheManager = CacheManager.create();
        }

        /**
         * 根据缓存名字获得某个缓存
         * @param cacheName
         * @return
         */
        public static Cache getCache(String cacheName) {
        return cacheManager.getCache(cacheName);
        }

        /**
         * 根据缓存名字,元素的key值,获得缓存中对应的value值对象。
         * @param cacheName
         * @param key
         * @param isRemoveKey
         * @return
         */
        public static Object getValue(String cacheName, Object key, boolean isRemoveKey) {
        Cache cache = getCache(cacheName);
        Element e = null;
        if (isRemoveKey) {
        e = cache.get(key);
        } else {
        e = cache.getQuiet(key);
        }
        if (e == null) {
        return null;
        }
        return e.getObjectValue();
        }

        /**
         * 根据缓存名字,元素的key值,获得缓存中对应的value值对象。
         * @param cacheName
         * @param key
         * @return
         */
        public static Object getValue(String cacheName, Object key) {
        return getValue(cacheName, key, false);
        }

        /**
         * 静态的获取元素,不会产生update.
         * @param cacheName
         * @param key
         * @return
         */
        public static Element getElementByQuite(String cacheName, Object key) {
        Cache cache = getCache(cacheName);
        return cache.getQuiet(key);
        }

        /**
         * 动态的获取元素,会产生update.
         * @param cacheName
         * @param key
         * @return
         */
        public static Element getElementByDynic(String cacheName, Object key){
        Cache cache = getCache(cacheName);
        return cache.get(key);
        }

        /**
         * 向某个缓存中添加元素
         * @param cacheName
         * @param key
         * @param value
         */
        public static void put(String cacheName, Object key, Object value) {
        Element element = new Element(key, value);
        getCache(cacheName).put(element);
        }

        /**
         * 移除某个缓存中的元素
         * @param cacheName
         * @param key
         */
        public static void remove(String cacheName, Object key) {
        Cache cache = getCache(cacheName);
        if (cache != null) {
        cache.remove(key);
        }
        }

        /**
         * 判断某个缓存是否包含某个元素
         * @param cacheName
         * @param key
         * @return
         */
        public static boolean contains(String cacheName, Object key) {
        Cache cache = getCache(cacheName);
        Element e = cache.get(key);
        if (e != null) {
        return true;
        }
        return false;
        }

        @SuppressWarnings("unchecked")
        public static <T> List<T> getKeys(String cacheName, Class<T> t) {
        Cache cache = getCache(cacheName);
        return (List<T>) cache.getKeys();
        }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123

闲言碎语

备注:缓存这一思想在很多场景下都适用

ehcache和redis缓存比较

ehcache直接在jvm虚拟机中缓存,速度快,效率高;但是缓存共享麻烦,集群分布式应用不方便。
redis是通过socket访问到缓存服务,效率比ecache低,比数据库要快很多,处理集群和分布式缓存方便,有成熟的方案。

取数逻辑,通常先到缓存对象中去查询,如果有查询到就直接返回,如果没有查询到就到数据库里查询,将查询结果存到缓存对象中,然后将数据返回给用户对象。



    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多