Java Ehcache缓存框架入门级使用实例

2025-05-29 0 106

前言

JAVA缓存实现方案有很多,最基本的自己使用Map去构建缓存,或者使用memcached或Redis,但是上述两种缓存框架都要搭建服务器,而Map自行构建的缓存可能没有很高的使用效率,那么我们可以尝试一下使用Ehcache缓存框架

Ehcache主要基于内存缓存,磁盘缓存为辅的,使用起来方便。下面介绍如何在项目中使用Ehcache

入门使用教程

1.maven引用

?

1
2

3

4

5
<dependency>

<groupId>net.sf.ehcache</groupId>

<artifactId>ehcache</artifactId>

<version>2.10.4</version>

</dependency>

2.在classpath下建立一个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

33

34

35

36

37

38

39

40

41

42

43

44

45
<?xml version="1.0" encoding="UTF-8"?>

<ehcache>

<!--timeToIdleSeconds 当缓存闲置n秒后销毁 -->

<!--timeToLiveSeconds 当缓存存活n秒后销毁 -->

<!--

缓存配置

name:缓存名称。

maxElementsInMemory:缓存最大个数。

eternal:对象是否永久有效,一但设置了,timeout将不起作用。

timeToIdleSeconds:设置对象在失效前的允许闲置时间(单位:秒)。仅当eternal=false对象不是永久有效时使用,可选属性,默认值是0,也就是可闲置时间无穷大。

timeToLiveSeconds:设置对象在失效前允许存活时间(单位:秒)。最大时间介于创建时间和失效时间之间。仅当eternal=false对象不是永久有效时使用,默认是0.,也就是对象存活时间无穷大。

overflowToDisk:当内存中对象数量达到maxElementsInMemory时,Ehcache将会对象写到磁盘中。

diskSpoolBufferSizeMB:这个参数设置DiskStore(磁盘缓存)的缓存区大小。默认是30MB。每个Cache都应该有自己的一个缓冲区。

maxElementsOnDisk:硬盘最大缓存个数。

diskPersistent:是否缓存虚拟机重启期数据 Whether the disk store persists between restarts of the Virtual Machine. The default value is false.

diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认是120秒。

memoryStoreEvictionPolicy:当达到maxElementsInMemory限制时,Ehcache将会根据指定的策略去清理内存。默认策略是LRU(最近最少使用)。你可以设置为FIFO(先进先出)或是LFU(较少使用)。

clearOnFlush:内存数量最大时是否清除。

-->

<!-- 磁盘缓存位置 -->

<diskStore path="java.io.tmpdir/easylink-mall-web/ehcache"/>

<!-- 默认缓存 -->

<defaultCache

maxElementsInMemory="10000"

eternal="false"

timeToIdleSeconds="120"

timeToLiveSeconds="120"

maxElementsOnDisk="10000000"

diskExpiryThreadIntervalSeconds="120"

memoryStoreEvictionPolicy="LRU">

<persistence strategy="localTempSwap"/>

</defaultCache>

<!-- 商户申请数据缓存 数据缓存40分钟 -->

<cache

name="merchant-apply-cache"

eternal="false"

timeToIdleSeconds="2400"

timeToLiveSeconds="2400"

maxEntriesLocalHeap="10000"

maxEntriesLocalDisk="10000000"

diskExpiryThreadIntervalSeconds="120"

overflowToDisk="false"

memoryStoreEvictionPolicy="LRU">

</cache>

</ehcache>

3.与spring的cacheManager结合使用

?

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
<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xmlns:cache="http://www.springframework.org/schema/cache"

xsi:schemaLocation="

http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans.xsd

http://www.springframework.org/schema/cache

http://www.springframework.org/schema/cache/spring-cache.xsd">

<!-- 支持缓存注解 -->

<cache:annotation-driven cache-manager="cacheManager" />

<!-- 默认是cacheManager -->

<bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager">

<property name="cacheManager" ref="cacheManagerFactory"/>

</bean>

<!-- cache管理器配置 -->

<bean id="cacheManagerFactory" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">

<property name="configLocation" value="classpath:ehcache.xml"/>

<property name="shared" value="true" />

</bean>

</beans>

4.代码使用

?

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
import org.junit.Test;

import org.junit.runner.RunWith;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.cache.Cache;

import org.springframework.cache.CacheManager;

import org.springframework.test.context.ContextConfiguration;

import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.baomidou.mybatisplus.toolkit.IdWorker;

import com.easylink.mall.entity.Merchant;

@RunWith(SpringJUnit4ClassRunner.class)

@ContextConfiguration(locations = "classpath:spring/spring.xml")

public class EhcacheTest {

@Autowired

private CacheManager cacheManager;

@Test

public void execute() {

// 获取商户申请缓存容器

Cache cache = cacheManager.getCache("merchant-apply-cache");

Merchant merchant = new Merchant();

Long id = IdWorker.getId();

merchant.setId(id);

merchant.setName("缓存测试");

// 将商户申请数据添加至缓存中 // key : id value : object

cache.put(id, merchant);

// 获取商户申请数据

// 方法1

Merchant cacheMerchant1 = (Merchant) cache.get(id).get();

System.out.println(cacheMerchant1.getName());

// 方法2

Merchant cacheMerchant2 = cache.get(id, Merchant.class);

System.out.println(cacheMerchant2.getName());

// 将商户申请数据从缓存中移除

cache.evict(id);

}

}

5.注意事项

cache.get(key) 和cache.get(key, class);方法,由于不知道你存入的key是什么类型,所以get的时候不会做key的类型检查,如上述例子中

?

1
2

3
Long id = IdWorker.getId();

cache.put(id, merchant);

Merchant cacheMerchant2 = cache.get(id, Merchant.class);

put进去时的key是Long类型的,get的时候也只能传入对应Long类型的key才能获取到对应的value,如果传入的是String类型的key,即使两个key的值是一致的,也会导致无法获取到对应的value。这个情况很容易发生在对request请求的参数,由于是String字符串类型,但是忘了做类型转换就直接把这个String当做key去获取对应的value。导致获取不到,请同学们要注意,亲身经历,血与泪的教训。

总结

以上就是我自己总结的Ehcache入门级用法,Ehcache是个不错的内存缓存框架,如果没使用过的话,可以尝试使用。希望对大家的学习有所帮助,也希望大家多多支持快网idc。

原文链接:http://www.jianshu.com/p/c1690f9d953e?utm_source=tuicool&utm_medium=referral

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 Java Ehcache缓存框架入门级使用实例 https://www.kuaiidc.com/115215.html

相关文章

发表评论
暂无评论