SpringBoot+Ehcache使用示例

Java教程 2025-09-30

摘要

本文介绍了SpringBoot中配置Ehcache、自定义get/set方式,并实际使用缓存的过程。

概念

Ehcache是一种Java缓存框架,支持多种缓存策略,如:

  • 最近最少使用LRU:当缓存达到最大容量时,会将最近最少使用的元素淘汰。
  • 最少最近使用LFU:根据元素被访问的频率来淘汰元素,最少被访问的元素会被优先淘汰。
  • 先进先出FIFO:按元素进入缓存的时间顺序淘汰元素,先进入的元素会被优先淘汰。

内存与磁盘持久化存储:

Ehcache支持将数据存储在内存中,以实现快速访问。当内存不足时,Ehcache可以将数据交换到磁盘,确保缓存数据不会因为内存限制而丢失。磁盘存储路径可以通过配置灵活指定,即使在系统重启后也能恢复缓存数据。提供多种持久化策略,包括本地临时交换localTempSwap和自定义持久化实现。

配置灵活性:

可通过配置ehcache.xml文件,放在启动类资源目录里,可自定义缓存策略,LRU,diskExpiryThreadIntervalSeconds。

编码示例

引入依赖:

pom.xml指定ehcache坐标并排除slf4j


<dependency>
    <groupId>net.sf.ehcachegroupId>
    <artifactId>ehcacheartifactId>
    <exclusions>
        <exclusion>
            <groupId>org.slf4jgroupId>
            <artifactId>slf4j-apiartifactId>
        exclusion>
    exclusions>
dependency>
<dependency>
    <groupId>net.sf.ehcachegroupId>
    <artifactId>ehcacheartifactId>
    <version>2.10.9.2version>
    <scope>compilescope>
dependency>
<dependency>
    <groupId>org.springframework.bootgroupId>
    <artifactId>spring-boot-starter-cacheartifactId>
dependency>

配置ehcache.xml文件:

<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd">
    <diskStore path="java.io.tmpdir/ehcache"/> 
    
    
    <defaultCache
            maxElementsInMemory="10000"
            eternal="false"
            timeToIdleSeconds="120"
            timeToLiveSeconds="120"
            maxElementsOnDisk="10000000"
            diskExpiryThreadIntervalSeconds="120"
            memoryStoreEvictionPolicy="LRU">
        <persistence strategy="localTempSwap"/>
    defaultCache>
    
    <cache name="cacheName"
           maxElementsInMemory="10000"
           eternal="false"
           timeToIdleSeconds="0"
           timeToLiveSeconds="0"
           maxElementsOnDisk="10000000"
           diskExpiryThreadIntervalSeconds="120"
           memoryStoreEvictionPolicy="LRU">
        <persistence strategy="localTempSwap"/>
    cache>
ehcache>

配置文件:

application.yml指定spring的缓存文件路径

spring:
  cache:
    type: ehcache
    ehcache:
      config: classpath:ehcache.xml

自定义缓存get/set方式:

利用CacheManager处理缓存:

package org.coffeebeans.ehcache;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 
  • ClassName: EhCacheService
  •  *
  • Author: OakWang
  •  */
    @Service public class EhCacheService {     @Autowired     private CacheManager cacheManager;     /**      * 根据名称获取缓存数据      * @param cacheName cache名称      * @param keyName cache中对应key名称      * @return cache数据      */     public List getCacheData(String cacheName, String keyName){        Cache cache = cacheManager.getCache(cacheName);        if (!Objects.isNull(cache)) {           Element element = cache.get(keyName);           if (!Objects.isNull(element)) {              return (List) element.getObjectValue();           }        }        return new ArrayList<>();     }     /**      * 往缓存中存放数据 名字区分      * @param cacheName     cache名称      * @param keyName       cache中对应key名称      * @param dataList      存放数据      */     public void putCacheData(String cacheName, String keyName, List dataList){        Cache cache = cacheManager.getCache(cacheName);        if (Objects.isNull(cache)){           cache = new Cache(cacheName,1000,true,false,0,0);        }        Element newElement = new Element(keyName, dataList);        cache.put(newElement);     } }

    启动类加注解:

    @EnableCaching开启程序缓存

    package org.coffeebeans;
    
    import lombok.extern.slf4j.Slf4j;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.cache.annotation.EnableCaching;
    
    /**
     * 
  • ClassName: EhCacheApplication
  •  *
  • Author: OakWang
  •  */
    @Slf4j @SpringBootApplication @EnableCaching//开启程序缓存 public class EhCacheApplication {     public static void main(String[] args) {        SpringApplication springApplication = new SpringApplication(EhCacheApplication.class);        springApplication.run(args);        log.info("EhCacheApplication start success!");     } }

    编辑测试类:

    package org.coffeebeans.ehcache;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    import java.util.Collections;
    import java.util.List;
    
    /**
     * 
  • ClassName: TestEhCache
  •  *
  • Author: OakWang
  •  */
    @Service public class TestEhCache {     @Autowired     private EhCacheService ehCacheService;     public void testEhCache() {        ehCacheService.putCacheData("cacheName""keyName", Collections.singletonList("value"));        List cacheData = ehCacheService.getCacheData("cacheName""keyName");        System.out.println("获取缓存数据:" + cacheData.toString());     } }

    测试结果:

    图片

    总结

    以上我们了解了SpringBoot中配置Ehcache、自定义get/set方式,并实际使用缓存的过程。

    关注公众号:咖啡Beans

    在这里,我们专注于软件技术的交流与成长,分享开发心得与笔记,涵盖编程、AI、资讯、面试等多个领域。无论是前沿科技的探索,还是实用技巧的总结,我们都致力于为大家呈现有价值的内容。期待与你共同进步,开启技术之旅。