SpringBoot 整合 Ehcache 实现缓存

本文详细介绍如何在SpringBoot项目中整合EhCache缓存,包括添加依赖、配置缓存、开启缓存、创建实体类、DAO及自定义缓存key生成器等步骤。

前文

SpringBoot 整合 JDBCTemplate

SpringBoot 整合 Redis 的简单使用

Spring 提供的缓存

从 Spring 3.1 开始对缓存提供了支持,核心思路是对方法的缓存,当开发者调用一个方法时,将方法的参数和返回值作为 key / value 缓存起来,当再次调用该方法时,如果缓存中有数据,就直接从缓存中读取,否则再去执行该方法。但是,Spring 中并未提供缓存的实现,而是提供了一套缓存的 API,开发者可以自由选择缓存的实现,目前 SpringBoot 支持的缓存有如下几种:

  • JCache(JSR-107)
  • EhCache 2.X
  • Hazelcast
  • Infinispan
  • Couchbase
  • Redis
  • Caffeine
  • Simple

EhCache

EhCache 缓存在 Java 开发领域已是久负盛名,在 SpringBoot 中,只需要一个配置文件就可以将 EhCache 集成到项目中

添加依赖

<dependencies>
	<!-- 导入 web -->
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-web</artifactId>
	</dependency>
	
	<!-- 导入 SpringBoot 与 Cache 的整合包-->
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-cache</artifactId>
	</dependency>
	
	<!-- 导入 Ehcache -->
	<dependency>
		<groupId>net.sf.ehcache</groupId>
		<artifactId>ehcache</artifactId>
	</dependency>
</dependencies>

创建缓存配置文件

如果 Ehcache 的依赖存在,并且在 classpath 下有一个名为 ehcache.xml 的 Ehcache 配置文件,那么 EhCacheCacheManager 将会自动作为缓存的实现。因此,在 resource 目录下创建 ehcache.xml 文件作为 Ehcache 缓存的配置文件,代码如下:

<ehcache>
    <diskStore path="java.io.tmpdir/cache" />
    <defaultCache
        maxElementsInMemory="10000"
        eternal="false"
        timeToIdleSeconds="120"
        timeToLiveSeconds="120"
        overflowToDisk="false"
        diskPersistent="false"
        diskExpiryThreadIntervalSeconds="120"
    />

    <!-- name 表示缓存名称 -->
    <!-- maxElementsInMemory 表示缓存的最大个数 -->
    <!-- eternal 表示缓存对象是否永久有效,一旦设置永久有效,那么 timeout 将不起作用 -->
    <!-- timeToIdleSeconds 表示缓存对象在失效前的允许闲置时间(单位:s),当 eternal 设置为 false 时该属性才生效 -->
    <!-- timeToLiveSeconds 表示缓存对象在失效前允许存活的时间(单位:s),当 eternal 设置为 false 时该属性才生效 -->
    <!-- overflowToDisk 表示当内存中的对象数量达到 maxElementsInMemory 时,Ehcache 是否将对象写进磁盘中  -->
    <!-- diskExpiryThreadIntervalSeconds 表示磁盘失效线程运行时间间隔 -->
    <cache name="user_cache"
          
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值