news 2026/5/2 9:14:51

SpringBoot项目里,除了Redis,试试这个更轻量的本地缓存Ehcache(附完整配置代码)

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
SpringBoot项目里,除了Redis,试试这个更轻量的本地缓存Ehcache(附完整配置代码)

SpringBoot项目中轻量级本地缓存Ehcache的实战指南

在中小型SpringBoot应用开发中,缓存技术是提升系统响应速度的利器。当项目规模尚未达到需要Redis这类分布式缓存时,一个轻量级的本地缓存方案往往能带来更简单的架构和更快的响应。Ehcache作为纯Java实现的进程内缓存框架,正是这种场景下的理想选择。

1. 为什么选择Ehcache而非Redis?

Redis固然强大,但并非所有场景都需要它的分布式特性。Ehcache与Redis的核心差异体现在几个方面:

  • 架构复杂度:Redis需要独立部署和维护,而Ehcache直接嵌入应用进程
  • 性能表现:本地内存访问比网络请求快1-2个数量级
  • 适用场景
    • Ehcache适合:单实例部署、数据量适中(GB级以内)、对延迟敏感的内部系统
    • Redis适合:分布式环境、大数据量、需要持久化和高可用的场景

实际项目中,我们经常看到这样的配置组合:

// 典型的多级缓存配置示例 @Configuration @EnableCaching public class CacheConfig { @Bean public CacheManager cacheManager() { return new ConcurrentMapCacheManager("localCache"); } @Bean public RedisCacheManager redisCacheManager(RedisConnectionFactory factory) { return RedisCacheManager.create(factory); } }

2. Ehcache 3.x的核心特性解析

Ehcache 3.x版本相比早期有了显著改进,主要特性包括:

2.1 分层存储架构

Ehcache支持灵活的多级存储策略,这是它最强大的特性之一:

存储层级访问速度容量限制GC影响典型用途
堆上存储最快受JVM堆大小限制受GC影响高频访问的小数据
堆外存储仅受物理内存限制无GC影响中等规模数据
磁盘存储较慢受磁盘空间限制无影响低频访问的大数据

配置示例:

<cache name="tieredCache" maxEntriesLocalHeap="1000" maxBytesLocalOffHeap="1G" overflowToDisk="true"> <persistence strategy="localTempSwap"/> </cache>

2.2 完善的Spring Cache集成

Ehcache 3.x通过JSR-107标准完美支持Spring Cache注解:

@Service public class ProductService { @Cacheable(cacheNames = "products", key = "#id") public Product getProductById(Long id) { // 数据库查询逻辑 } @CacheEvict(cacheNames = "products", key = "#product.id") public void updateProduct(Product product) { // 更新逻辑 } }

3. SpringBoot集成Ehcache实战

3.1 基础环境配置

首先添加Maven依赖:

<dependencies> <dependency> <groupId>org.ehcache</groupId> <artifactId>ehcache</artifactId> <version>3.10.0</version> </dependency> <dependency> <groupId>javax.cache</groupId> <artifactId>cache-api</artifactId> </dependency> </dependencies>

创建ehcache.xml配置文件:

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.ehcache.org/v3" xsi:schemaLocation="http://www.ehcache.org/v3 http://www.ehcache.org/schema/ehcache-core-3.0.xsd"> <cache alias="products"> <key-type>java.lang.Long</key-type> <value-type>com.example.Product</value-type> <heap unit="entries">1000</heap> <expiry> <ttl unit="minutes">30</ttl> </expiry> </cache> <cache alias="users"> <key-type>java.lang.String</key-type> <value-type>com.example.User</value-type> <heap unit="entries">500</heap> <offheap unit="MB">50</offheap> <expiry> <tti unit="hours">2</tti> </expiry> </cache> </config>

3.2 SpringBoot自动配置

在application.properties中启用Ehcache:

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

创建配置类确保正确初始化:

@Configuration @EnableCaching public class EhcacheConfig { @Bean public JCacheManagerCustomizer cacheManagerCustomizer() { return cm -> { CachingProvider provider = Caching.getCachingProvider(); CacheManager cacheManager = provider.getCacheManager( getClass().getResource("/ehcache.xml").toURI(), getClass().getClassLoader() ); // 预热缓存 cacheManager.getCache("products", Long.class, Product.class); cacheManager.getCache("users", String.class, User.class); }; } }

4. 高级特性与性能优化

4.1 缓存监控与管理

Ehcache提供了丰富的监控指标,可以通过JMX暴露:

@Bean public EhcacheStatisticsMXBean ehcacheStatistics(CacheManager cacheManager) { ManagementService.registerCacheManager( ((Eh107CacheManager) cacheManager).getCacheManager(), ManagementServiceConfigurationBuilder .newConfigurationBuilder() .build() ); return new EhcacheStatistics(cacheManager); }

关键监控指标包括:

  • 缓存命中率
  • 缓存项数量
  • 堆/堆外内存使用量
  • 磁盘存储情况

4.2 缓存一致性策略

对于多实例部署环境,Ehcache支持多种复制策略:

<cache name="replicatedCache"> <heap unit="entries">1000</heap> <listeners> <listener> <class>org.ehcache.clustered.client.config.ClusteredStoreConfiguration</class> <event-firing-mode>ASYNCHRONOUS</event-firing-mode> <event-ordering-mode>UNORDERED</event-ordering-mode> <events-to-fire-on>CREATED</events-to-fire-on> <events-to-fire-on>UPDATED</events-to-fire-on> <events-to-fire-on>EXPIRED</events-to-fire-on> <events-to-fire-on>REMOVED</events-to-fire-on> <events-to-fire-on>EVICTED</events-to-fire-on> </listener> </listeners> </cache>

4.3 性能调优建议

根据实际项目经验,以下配置可以显著提升Ehcache性能:

  1. 合理设置堆外内存

    <cache-template name="offheapTemplate"> <offheap unit="MB">100</offheap> </cache-template>
  2. 优化过期策略

    <expiry> <ttl unit="minutes">30</ttl> <!-- 或者 --> <tti unit="hours">2</tti> </expiry>
  3. 配置磁盘存储路径

    <persistence directory="/data/ehcache"/>
  4. 调整线程池大小

    CacheManagerBuilder.newCacheManagerBuilder() .using(PooledExecutionServiceConfigurationBuilder .newPooledExecutionServiceConfigurationBuilder() .pool("default", 1, 10) .build()) .build(true);

5. 常见问题解决方案

5.1 缓存穿透防护

@Cacheable(cacheNames = "products", key = "#id", unless = "#result == null") public Product getProduct(Long id) { Product product = productRepository.findById(id); if(product == null) { // 空值缓存策略 cacheNullValue(id); } return product; } private void cacheNullValue(Long id) { // 使用特殊值标记空结果 cacheManager.getCache("products").put(id, NULL_OBJECT); }

5.2 缓存雪崩预防

@Bean public CacheManagerCustomizer<JCacheCacheManager> cacheManagerCustomizer() { return cm -> { CachingProvider provider = Caching.getCachingProvider(); CacheManager cacheManager = provider.getCacheManager(); MutableConfiguration<Long, Product> config = new MutableConfiguration<>() .setExpiryPolicyFactory( FactoryBuilder.factoryOf( new CreatedExpiryPolicy( new Duration(TimeUnit.MINUTES, 30 + new Random().nextInt(15)) // 随机过期时间 ) ) ); cacheManager.createCache("products", config); }; }

5.3 大对象缓存优化

对于大型对象,建议采用分块缓存策略:

public Product getLargeProduct(Long id) { Product product = cache.get(id); if(product == null) { product = loadProductInChunks(id); } return product; } private Product loadProductInChunks(Long id) { Product product = new Product(); // 缓存基本信息 cache.put(id + "_base", product.getBaseInfo()); // 分批缓存图片数据 for(int i=0; i<product.getImages().size(); i++) { cache.put(id + "_img_" + i, product.getImages().get(i)); } return product; }

在项目实践中发现,Ehcache的配置需要根据实际数据访问模式不断调整。例如,对于读多写少的数据,可以适当增加缓存大小和过期时间;而对于频繁变更的数据,则需要更短的TTL和更积极的失效策略。

版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/5/2 9:13:41

py之关于网站字体反爬时woff文件该如何得到真实映射

例如有这么一份woff文件: 可以观察到字符的unicode并非是真实的,所以为了提取真实的字符,分享以下脚本: from fontTools.ttLib import TTFont from fontTools.ttLib.woff2 import decompress from PIL import ImageFont, Image, ImageDraw from io import BytesIO import d…

作者头像 李华
网站建设 2026/5/2 9:13:34

柔性数据库设计:为AI Agent打造动态Schema的数据存储方案

1. 项目概述&#xff1a;一个为AI Agent设计的柔性数据库框架如果你经常和Claude、Cursor这类AI编程助手打交道&#xff0c;想让它帮你管理点东西——比如零散的笔记、收集的网页片段、或者自己定义的各种表单数据——那你大概率会遇到一个头疼的问题&#xff1a;数据库的Schem…

作者头像 李华
网站建设 2026/5/2 9:08:26

3步掌握NHSE:动物森友会存档编辑器的深度应用指南

3步掌握NHSE&#xff1a;动物森友会存档编辑器的深度应用指南 【免费下载链接】NHSE Animal Crossing: New Horizons save editor 项目地址: https://gitcode.com/gh_mirrors/nh/NHSE NHSE&#xff08;New Horizons Save Editor&#xff09;是一款专为《集合啦&#xff…

作者头像 李华
网站建设 2026/5/2 9:02:57

Kai 9000:构建具备持久记忆与跨平台执行能力的开源AI助手

1. 项目概述&#xff1a;一个全平台、开源的智能体新范式 如果你和我一样&#xff0c;对市面上那些“健忘”的AI助手感到厌倦&#xff0c;每次对话都像在和一个失忆症患者重新认识&#xff0c;那么你可能会对Kai 9000产生兴趣。这不是又一个套壳的ChatGPT前端&#xff0c;而是一…

作者头像 李华