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

 更新时间:2017年08月11日 10:47:19   作者:liangzzz  
这篇文章主要介绍了Java Ehcache缓存框架入门级使用实例,具有一定的参考价值,感兴趣的小伙伴们可以参考一下。

前言

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

总结

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

相关文章

  • 带你快速上手Servlet

    带你快速上手Servlet

    这篇文章主要介绍了带你快速上手Servlet,文中有非常详细的代码示例,对正在学习java的小伙伴们有很好的帮助,需要的朋友可以参考下
    2021-05-05
  • SpringBoot实现自定义条件注解的代码示例

    SpringBoot实现自定义条件注解的代码示例

    在Spring Boot中,条件注解是一种非常强大的工具,它可以根据特定的条件来选择是否加载某个类或某个Bean,文将介绍如何在Spring Boot中实现自定义条件注解,并提供一个示例代码,需要的朋友可以参考下
    2023-06-06
  • Java程序员编程性能优化必备的34个小技巧(总结)

    Java程序员编程性能优化必备的34个小技巧(总结)

    这篇文章主要介绍了Java程序员编程性能优化必备的34个小技巧(总结),小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2019-07-07
  • Java的Spring框架下的AOP编程模式示例

    Java的Spring框架下的AOP编程模式示例

    这篇文章主要介绍了Java的Spring框架下的AOP编程模式示例,文中分别讲到了基于XML和基于@AspectJ的自定义方式,需要的朋友可以参考下
    2015-12-12
  • 每日几道java新手入门面试题,通往自由的道路

    每日几道java新手入门面试题,通往自由的道路

    这篇文章主要为大家分享了最有价值的是几道java面试题,涵盖内容全面,包括数据结构和算法相关的题目、经典面试编程题等,对hashCode方法的设计、垃圾收集的堆和代进行剖析,感兴趣的小伙伴们可以参考一下
    2021-07-07
  • ElasticSearch查询文档基本操作实例

    ElasticSearch查询文档基本操作实例

    这篇文章主要为大家介绍了ElasticSearch查询文档基本操作实例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-02-02
  • Java的Integer缓存池用法

    Java的Integer缓存池用法

    Java的Integer缓存池主要为了提升性能和节省内存,它缓存了-128到127范围内的Integer对象,因此这些对象在比较时会直接比较引用,而不是值,其他包装类如Byte、Short、Character也有类似的缓存池
    2025-02-02
  • Java如何实现验证码验证功能

    Java如何实现验证码验证功能

    这篇文章主要教大家如何实现Java验证码验证功能,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2018-02-02
  • SpringBoot+Vue项目新手快速入门指南

    SpringBoot+Vue项目新手快速入门指南

    最近刚刚做了一个基于vue+springboot的系统,于是基于这点,对遇到的一些问题进行一些配置的汇总,下面这篇文章主要给大家介绍了关于SpringBoot+Vue项目新手快速入门的相关资料,需要的朋友可以参考下
    2022-06-06
  • Spring Boot项目中集成微信支付v3

    Spring Boot项目中集成微信支付v3

    这篇文章主要介绍了Spring Boot项目中集成微信支付v3,帮助大家更好的理解和使用spring boot框架,感兴趣的朋友可以了解下
    2021-01-01

最新评论