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

作者:liangzzz 时间:2022-08-23 20:51:54 

前言

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

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

入门使用教程

1.maven引用


<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>2.10.4</version>
</dependency>

2.在classpath下建立一个ehcache.xml


<?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结合使用


<?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.代码使用


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的类型检查,如上述例子中


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。导致获取不到,请同学们要注意,亲身经历,血与泪的教训。

来源:http://www.jianshu.com/p/c1690f9d953e?utm_source=tuicool&utm_medium=referral

标签:Java,Ehcache,缓存
0
投稿

猜你喜欢

  • 使用Springboot根据配置文件动态注入接口实现类

    2022-11-18 06:56:45
  • java实现幸运抽奖功能

    2023-11-27 07:24:16
  • C++高并发内存池的整体设计和实现思路

    2023-07-03 16:29:31
  • Java里的static在Kotlin里如何实现

    2023-08-24 20:25:33
  • Java常用流程控制语句实现原理解析

    2023-11-08 14:11:34
  • VS2019配置opencv详细图文教程和测试代码的实现

    2023-07-17 13:49:31
  • 阿里开源Java诊断工具神器使用及场景详解

    2023-11-06 17:24:21
  • SpringBoot如何读取war包jar包和Resource资源

    2023-11-09 01:40:44
  • 在Android设备上搭建Web服务器的方法

    2023-06-23 23:38:36
  • 深入理解java动态代理的两种实现方式(JDK/Cglib)

    2023-11-26 13:29:52
  • Java的Spring框架下的AOP编程模式示例

    2023-11-02 00:52:25
  • Java以命令模式设计模式

    2023-11-24 21:27:52
  • Servlet实现文件的上传与下载

    2023-08-08 06:13:43
  • Java IO流相关知识代码解析

    2023-08-05 05:48:04
  • Java设计模式的事件模型详解

    2023-11-29 04:47:08
  • opencv利用鼠标滑动画出多彩的形状

    2023-11-03 05:20:57
  • Java java.sql.Timestamp时间戳案例详解

    2023-11-10 13:50:47
  • Java8 Comparator源码演示及解析

    2023-09-18 10:51:12
  • Swift洗牌动画效果的实现方法

    2023-06-21 14:01:56
  • 浅析Java线程的中断机制

    2023-11-19 20:11:50
  • asp之家 软件编程 m.aspxhome.com