EhCache使用

简介:

EhCache 是一个纯Java的进程内缓存框架,具有快速、精干等特点,是Hibernate中默认的CacheProvider。


非常简单,而且易用。

    ehcache 是一个非常轻量级的缓存实现,而且从1.2 之后就支持了集群,而且是hibernate 默认的缓存provider。ehcache 是一个纯Java的进程内缓存框架,具有快速、精干等特点,是Hibernate中默认的CacheProvider

ehcache可以直接使用。也可以和Hibernate对象/关系框架结合使用。还可以做Servlet缓存。

Cache 存储方式 :内存或磁盘。

主要特征:

1. 快速.

2. 简单.

3. 多种缓存策略

4. 缓存数据有两级:内存和磁盘,因此无需担心容量问题

5. 缓存数据会在虚拟机重启的过程中写入磁盘

6. 可以通过RMI、可插入API等方式进行分布式缓存

7. 具有缓存和缓存管理器的侦听接口

8. 支持多缓存管理器实例,以及一个实例的多个缓存区域

9. 提供Hibernate的缓存实现

10. 等等


①创建ehcache.xml

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
<? xml  version = "1.0"  encoding = "UTF-8" ?>
< ehcache  xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" 
         xsi:noNamespaceSchemaLocation = "http://ehcache.org/ehcache.xsd"  updateCheck = "false" >  
    <!-- 设置磁盘持久化的位置 -->  
     < diskStore  path = "E:/temp"  />   
     < defaultCache  maxElementsInMemory = "10000"  eternal = "true"  overflowToDisk = "true"  />  
     < cache  name = "kentrasoftCache"  
            maxElementsInMemory = "0"  
            maxElementsOnDisk = "90000"   
            eternal = "false"   
            overflowToDisk = "true"   
            diskSpoolBufferSizeMB = "2048"  
            timeToIdleSeconds = "7200"   
            timeToLiveSeconds = "7200"   
            memoryStoreEvictionPolicy = "LFU"  
            diskPersistent = "true"   
            logging = "false"  
             />  
       <!--  
     name:Cache的唯一标识  
     maxElementsInMemory:内存中最大缓存对象数  
     maxElementsOnDisk:磁盘中最大缓存对象数,若是0表示无穷大  
     eternal:Element是否永久有效,一但设置了,timeout将不起作用  
     overflowToDisk:配置此属性,当内存中Element数量达到maxElementsInMemory时,Ehcache将会Element写到磁盘中  
     timeToIdleSeconds:设置Element在失效前的允许闲置时间。仅当element不是永久有效时使用,可选属性,默认值是0,也就是可闲置时间无穷大  
     timeToLiveSeconds:设置Element在失效前允许存活时间。最大时间介于创建时间和失效时间之间。仅当element不是永久有效时使用,默认是0.,也就是element存活时间无穷大   
     diskPersistent:是否缓存虚拟机重启期数据  
     diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认是120秒  
     diskSpoolBufferSizeMB:这个参数设置DiskStore(磁盘缓存)的缓存区大小。默认是30MB。每个Cache都应该有自己的一个缓冲区  
      memoryStoreEvictionPolicy:当达到maxElementsInMemory限制时,Ehcache将会根据指定的策略去清理内存。默认策略是LRU(最近最少使用)。你可以设置为FIFO(先进先出)或是LFU(较少使用)   
     -->  
</ ehcache >

②引入依赖

1
2
3
4
5
< dependency >
     < groupId >net.sf.ehcache</ groupId >
     < artifactId >ehcache</ artifactId >
     < version >2.9.1</ version >
</ dependency >

③EhCacheUtil类

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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
package com.kentrasoft.util;
 
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
 
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
 
public class EhCacheUtil {
     private static Cache kentrasoftCache;
     private static CacheManager manager;
     private static EhCacheUtil instance;
 
     static {
         // init();
     }
 
     public static Cache getKentrasoftCache() {
         return kentrasoftCache;
     }
 
 
     public static CacheManager getManager() {
         return manager;
     }
 
     public static EhCacheUtil init() {
         System.setProperty("net.sf.ehcache.enableShutdownHook", "true");
         if (instance == null) {
             instance = new EhCacheUtil();
             manager = CacheManager.create(EhCacheUtil.class.getClassLoader().getResourceAsStream("ehcache/ehcache.xml"));
             kentrasoftCache = manager.getCache("kentrasoftCache");
         }
         return instance;
 
     }
 
     public static EhCacheUtil init(String path) {
         System.setProperty("net.sf.ehcache.enableShutdownHook", "true");
         if (instance == null) {
             instance = new EhCacheUtil();
             manager = CacheManager.create(EhCacheUtil.class.getClassLoader().getResourceAsStream(path));
             kentrasoftCache = manager.getCache("kentrasoftCache");
         }
         return instance;
 
     }
 
     private static boolean isNull(Element e) {
         return e == null || e.getObjectValue() == null || e.getObjectValue() == null;
     }
 
     /**
      * 存入
      * @param < T >
      * @param cache 缓存库
      * @param key   键
      * @param value 值
      */
     public static < T  extends Serializable> void put(Cache cache, String key, T value) {
         Element e = new Element(key, value);
         cache.put(e);
         cache.flush();
     }
 
     /**
      * 存入 并设置元素是否永恒保存
      * @param < T >
      * @param cache  缓存库
      * @param key 键
      * @param value 值
      */
     public static < T  extends Serializable> void put(Cache cache, String key, T value, boolean eternal) {
         Element element = new Element(key, value);
         element.setEternal(eternal);
         cache.put(element);
         cache.flush();
     }
 
     /**
      * 存入
     
      * @param < T >
      * @param cache 缓存库
      * @param key 键
      * @param value 值
      * @param timeToLiveSeconds 最大存活时间
      * @param timeToIdleSeconds 最大访问间隔时间
      */
     public static < T  extends Serializable> void put(Cache cache, String key, T value, int timeToLiveSeconds,
             int timeToIdleSeconds) {
         Element element = new Element(key, value);
         element.setTimeToLive(timeToLiveSeconds);
         element.setTimeToIdle(timeToIdleSeconds);
         cache.put(element);
         cache.flush();
     }
 
     public static Object getCacheElement(Cache cache, String key) {
         Element e = cache.get(key);
         return e;
     }
 
     public static Object get(Cache cache, String key) {
         Element e = cache.get(key);
         if (e != null) {
             return e.getObjectValue();
         }
         return null;
     }
 
     public static void remove(Cache cache, String key) {
         cache.remove(key);
     }
 
     public static void removeAll(Cache cache, Collection< String > keys) {
         cache.removeAll(keys);
     }
 
     @SuppressWarnings("unchecked")
     public static void addToList(Cache cache, String key, Serializable value) {
         Element e = cache.get(key);
         if (isNull(e)) {
             List< Serializable > list = Collections.synchronizedList(new LinkedList< Serializable >());
             list.add(value);
             e = new Element(key, list);
             e.setEternal(true);
             cache.put(e);
         } else {
             List< Serializable > list = (List< Serializable >) e.getObjectValue();
             list.add(value);
             e = new Element(key, list);
             e.setEternal(true);
             cache.put(e);
         }
 
         cache.flush();
     }
 
     @SuppressWarnings("unchecked")
     public static void addAllToList(Cache cache, String key, Collection<? extends Serializable> value) {
         Element e = cache.get(key);
         if (isNull(e)) {
             List< Serializable > list = Collections.synchronizedList(new LinkedList< Serializable >());
             list.addAll(value);
             e = new Element(key, list);
             e.setEternal(true);
             cache.put(e);
         } else {
             List< Serializable > list = (List< Serializable >) e.getObjectValue();
             list.addAll(value);
             e = new Element(key, list);
             e.setEternal(true);
             cache.put(e);
         }
 
         cache.flush();
     }
 
     @SuppressWarnings("unchecked")
     public static void addToHashSet(Cache cache, String key, Serializable value) {
         Element e = cache.get(key);
         if (isNull(e)) {
             Set< Serializable > list = Collections.synchronizedSet(new HashSet< Serializable >());
             list.add(value);
             e = new Element(key, list);
             e.setEternal(true);
             cache.put(e);
         } else {
             Set< Serializable > list = (Set< Serializable >) e.getObjectValue();
             list.add(value);
             e = new Element(key, list);
             e.setEternal(true);
             cache.put(e);
         }
 
         cache.flush();
     }
 
     @SuppressWarnings("unchecked")
     public static void addAllToHashSet(Cache cache, String key, Collection<? extends Serializable> value) {
         Element e = cache.get(key);
         if (isNull(e)) {
             Set< Serializable > list = Collections.synchronizedSet(new HashSet< Serializable >());
             list.addAll(value);
             e = new Element(key, list);
             e.setEternal(true);
             cache.put(e);
         } else {
             Set< Serializable > list = (Set< Serializable >) e.getObjectValue();
             list.addAll(value);
             e = new Element(key, list);
             e.setEternal(true);
             cache.put(e);
         }
 
         cache.flush();
     }
 
     @SuppressWarnings("unchecked")
     public static void addToArrayList(Cache cache, String key, Serializable value) {
         Element e = cache.get(key);
         if (isNull(e)) {
             List< Serializable > list = Collections.synchronizedList(new ArrayList< Serializable >());
             list.add(value);
             e = new Element(key, list);
             e.setEternal(true);
             cache.put(e);
         } else {
             List< Serializable > list = (List< Serializable >) e.getObjectValue();
             list.add(value);
             e = new Element(key, list);
             e.setEternal(true);
             cache.put(e);
         }
 
         cache.flush();
     }
 
     @SuppressWarnings("unchecked")
     public static void addAllToArrayList(Cache cache, String key, Collection<? extends Serializable> value) {
         Element e = cache.get(key);
         if (isNull(e)) {
             List< Serializable > list = Collections.synchronizedList(new ArrayList< Serializable >());
             list.addAll(value);
             e = new Element(key, list);
             e.setEternal(true);
             cache.put(e);
         } else {
             List< Serializable > list = (List< Serializable >) e.getObjectValue();
             list.addAll(value);
             e = new Element(key, list);
             e.setEternal(true);
             cache.put(e);
         }
 
         cache.flush();
     }
 
     @SuppressWarnings("unchecked")
     public static < T  extends Serializable> T popFromList(Cache cache, String key, Class< T > T) {
         Element e = cache.get(key);
         if (e != null) {
             List< Serializable > list = (List< Serializable >) e.getObjectValue();
             Iterator< Serializable > it = list.iterator();
             if (list.size() > 0) {
                 Serializable obj = it.next();
                 it.remove();
                 e = new Element(key, list);
                 e.setEternal(true);
                 cache.put(e);
                 cache.flush();
                 return (T) obj;
             }
         }
         return null;
     }
 
     @SuppressWarnings("unchecked")
     public static < T  extends Serializable> List< T > popFromList(Cache cache, String key, int count, Class< T > T) {
         Element e = cache.get(key);
         if (e != null) {
             List< Serializable > list = (List< Serializable >) e.getObjectValue();
 
             if (count < 1) {
                 List< T > result = (List< T >) new ArrayList< Serializable >(list);
                 list.clear();
                 e = new Element(key, list);
                 e.setEternal(true);
                 cache.put(e);
                 cache.flush();
                 return result;
             }
 
             List< T > result = new ArrayList< T >(count);
             Iterator< Serializable > it = list.iterator();
             for (int i = 0; i < count && it.hasNext(); i++) {
                 Serializable obj = it.next();
                 it.remove();
                 result.add((T) obj);
             }
 
             e = new Element(key, list);
             e.setEternal(true);
             cache.put(e);
             cache.flush();
             return result;
         }
         return null;
     }
 
     @SuppressWarnings("unchecked")
     public static < T  extends Serializable> T popFromHashSet(Cache cache, String key, Class< T > T) {
         Element e = cache.get(key);
         if (e != null) {
             Set< Serializable > list = (Set< Serializable >) e.getObjectValue();
             Iterator< Serializable > it = list.iterator();
             if (list.size() > 0) {
                 Serializable obj = it.next();
                 it.remove();
                 e = new Element(key, list);
                 e.setEternal(true);
                 cache.put(e);
                 cache.flush();
                 return (T) obj;
             }
         }
         return null;
     }
 
     @SuppressWarnings("unchecked")
     public static < T  extends Serializable> List< T > popFromHashSet(Cache cache, String key, int count, Class< T > T) {
         Element e = cache.get(key);
         if (e != null) {
             Set< Serializable > list = (Set< Serializable >) e.getObjectValue();
 
             if (count < 1) {
                 List< T > result = (List< T >) new ArrayList< Serializable >(list);
                 list.clear();
                 e = new Element(key, list);
                 e.setEternal(true);
                 cache.put(e);
                 cache.flush();
                 return result;
             }
 
             List< T > result = new ArrayList< T >(count);
             Iterator< Serializable > it = list.iterator();
             for (int i = 0; i < count && it.hasNext(); i++) {
                 Serializable obj = it.next();
                 it.remove();
                 result.add((T) obj);
             }
 
             e = new Element(key, list);
             e.setEternal(true);
             cache.put(e);
             cache.flush();
             return result;
         }
         return null;
     }
 
     @SuppressWarnings("unchecked")
     public static int getCollectionSize(Cache cache, String key) {
         Element e = cache.get(key);
         if (e != null) {
             Collection< Serializable > list = (Collection< Serializable >) e.getObjectValue();
             return list.size();
         }
         return 0;
     }
 
     @SuppressWarnings("rawtypes")
     public static List getKeys(Cache cache) {
         return cache.getKeys();
     }
     
     /**获取缓存名称集合
      * @param cache Cache对象
      * @param start 开始位置
      * @return
      */
     public static List< String > getKeys(Cache cache, String start) {
         List<?> list = cache.getKeys();
         List< String > result = new ArrayList< String >(list.size());
         for (Object obj : list) {
             if (obj != null && obj.getClass() == String.class) {
                 String s = (String) obj;
                 if (s.startsWith(start))
                     result.add(s);
             }
         }
         return result;
     }
}

④使用示例:

1
2
3
4
5
6
//tokenId放入缓存中
EhCacheUtil.init();
EhCacheUtil.put(EhCacheUtil.getKentrasoftCache(),"tokenId","18484165");
 
// 获取令牌 tokenId
String tokenId = EhCacheUtil.get(EhCacheUtil.getKentrasoftCache(), "tokenId").toString();


其他相关对ehcache请参考

http://blog.csdn.net/l271640625/article/details/20528573







      本文转自建波李 51CTO博客,原文链接:http://blog.51cto.com/jianboli/1983542,如需转载请自行联系原作者




相关文章
|
5月前
|
SQL 缓存 Java
Hibernate - 整合Ehcache二级缓存使用详解
Hibernate - 整合Ehcache二级缓存使用详解
30 0
|
缓存 NoSQL Java
ehcache介绍
ehcache介绍
116 0
|
缓存 Java 数据库连接
Mybatis 整合 ehcache缓存
Mybatis 整合 ehcache缓存
191 0
|
缓存 Java 数据格式
Hibernate5.x 整合Ehcache
首先整理一下hibernate中关于缓存的知识点 一级缓存 仅当前事物能够访问,如果事务结束,则缓存也会结束 evict()将某对象从一级缓存中清除 clear()将一级缓存中的所有对象清除 get()/load()都支持一级缓存的读和写 save...
1533 0
|
缓存 Java 数据库连接
Hibernate Ehcache 配置
hibernate 默认使用 ehcache 缓存策略 ehcache 配置 hibernate 配置 true true org.
974 0
|
缓存 Java Spring
Ehcache整合spring配置
为了提高系统的运行效率,引入缓存机制,减少数据库访问和磁盘IO。下面说明一下ehcache和spring整合配置。 1.
789 0
|
存储 缓存 NoSQL
我们究竟什么时候可以使用Ehcache缓存(转)
一、Ehcache是什么 EhCache是Hibernate的二级缓存技术之一,可以把查询出来的数据存储在内存或者磁盘,节省下次同样查询语句再次查询数据库,大幅减轻数据库压力。 二、Ehcache的使用场景是什么 1、首先最主要就是页面缓存。
1368 0
|
缓存 NoSQL Java
玩转EhCache之最简单的缓存框架
一、简介 Ehcache是一个用Java实现的使用简单,高速,实现线程安全的缓存管理类库,ehcache提供了用内存,磁盘文件存储,以及分布式存储方式等多种灵活的cache管理方案。
1568 0
|
SQL 缓存 Java
ehcache + spring+mybatis整合
一、 Mybatis+Ehcache配置     为了提高MyBatis的性能,有时候我们需要加入缓存支持,目前用的比较多的缓存莫过于ehcache缓存了,ehcache性能强大,而且位各种应用都提供了解决方案,在此我们主要是做查询缓存,提高查询的效率.     整合MyBatis和ehcache需要的jar包如下: ehcache-core-2.4.4.jar
2229 0
|
Java 缓存 容器
Ehcache学习笔记
Ehcache是一种广泛使用的开源Java分布式缓存,主要面向通用缓存,Java EE和轻量级容器。本博文使用3.x版本。 maven包含依赖 &lt;dependency&gt; &lt;groupId&gt;org.ehcache&lt;/groupId&gt; &lt;artifactId&gt;ehcache&lt;/artifac
1104 0