1、简述
Ehcache 是 Java 平台下一个开源、高性能的分布式缓存框架,常用于提高系统性能和可扩展性。它能够帮助开发者缓存频繁访问的数据,从而减少对数据库和其他持久化存储的访问压力。
2、为什么选择 Ehcache?
- 高性能:支持内存和磁盘存储,能快速响应数据请求。
- 灵活性:支持多种存储配置和淘汰策略。
- 简单易用:轻量级,易于集成,支持 JSR-107(JCache)标准。
- 持久化支持:可以选择性地将缓存数据持久化到磁盘。
- 分布式扩展:支持集群化部署。
3、Spring Boot 集成 Ehcache
Spring Boot 集成 Ehcache,要注意Spring 的版本,一般Spring 2.x支持Ehcache,但是在Spring 3.x已经移除 Ehcache的类型。
3.1 Maven 引用
在使用 Ehcache 之前,需要添加其依赖。以下是 Ehcache 的 Maven 依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
</dependency>
3.2 配置 Ehcache
Ehcache 可以通过编程方式或 XML 文件进行配置。创建一个 ehcache.xml 文件放在资源目录(src/main/resources)中:
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="../config/ehcache.xsd">
<diskStore path="java.io.tmpdir"/>
<defaultCache
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
maxElementsOnDisk="10000000"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU">
<persistence strategy="localTempSwap"/>
</defaultCache>
<!-- My cache strategy. The name attribute value of the custom cache strategy is users. If you define multiple cache strategies, the name values cannot be the same. -->
<cache name="myCache"
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
maxElementsOnDisk="10000000"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU">
<persistence strategy="localTempSwap"/>
</cache>
</ehcache>
在项目的配置文件application.properties 指定Ehcache 配置路径和Spring Cache的缓存类型:
spring.cache.type=ehcache
spring.cache.ehcache.config=classpath:ehcache.xml
3.3 Cache运用
首先我们要在全局启动类中开启@EnableCaching缓存:
@SpringBootApplication
@EnableCaching
public class ShopEurekaApplication {
public static void main(String[] args) {
SpringApplication.run(ShopEurekaApplication.class, args);
}
}
创建一个用户的测试服务接口,通过@Cacheable 注解 来实现当前接口的缓存:
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
@Service
public class UserService {
@Cacheable(value = "myCache", key = "#id")
public String getUserById(String id) {
System.out.println("查询数据库...");
return "User-" + id;
}
}
通过定义的控制层来调用当前接口,当你多次调用的时候,直接走缓存快速返回:
import com.lm.shop.shopeureka.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/getUserById")
public String getUserById(@RequestParam String id) {
String userId = userService.getUserById(id);
return "Order created with ID: " + userId;
}
}
4、应用场景
除了基本的缓存功能,Ehcache在高级场景中也能实现更复杂和高效的应用。以下是一些高级应用案例:
- 多级缓存架构
Ehcache支持多级缓存(例如:内存和磁盘缓存)。这种结构可以优化性能和资源使用:
内存级缓存:用于快速访问频繁使用的数据。
磁盘级缓存:用于存储不经常访问但仍需要缓存的数据。
应用场景:处理大规模数据集(例如,电商系统的商品详情缓存),确保重要数据快速访问,同时保留大量数据可用性。 - 分布式缓存
通过与Terracotta Server Array或其他集成,Ehcache可以配置为分布式缓存以共享缓存数据:
高可用性:在多实例部署中,缓存数据可跨多个节点共享。
数据一致性:支持一致性策略,适用于需要共享会话或状态的分布式系统。
应用场景:跨多个微服务共享用户会话信息。 - 动态更新策略
Ehcache支持自定义的缓存刷新机制:
基于时间的刷新:TTL(Time-to-Live)和TTI(Time-to-Idle)。
实时数据推送:结合消息队列(如Kafka),动态更新缓存数据。
应用场景:证券系统实时更新股票行情。 - 查询缓存
对于复杂的数据库查询,可以缓存查询结果:
Hibernate二级缓存:与Hibernate结合缓存实体、集合及查询结果。
直接缓存SQL查询结果:避免重复查询数据库。
应用场景:如报表系统的多维分析查询。 - 自定义缓存加载器
使用Ehcache的CacheLoader接口实现缓存预加载:
批量加载:在应用启动时,预加载关键数据。
缓存回填:当缓存中没有数据时,自动从数据库或API填充数据。
应用场景:应用启动时加载热门商品列表。 - 事务支持
Ehcache提供与事务结合的支持:
XA Transactions:与分布式事务结合,确保数据一致性。
应用场景:金融系统中与多数据源的复杂事务处理。 - 大规模流量优化
结合Ehcache与CDN或反向代理优化高并发请求:
将缓存的静态内容直接返回,减少后端服务压力。
应用场景:热点文章页面或流量激增的直播活动页面。 - 缓存指标与监控
Ehcache提供丰富的监控功能,可与JMX和Prometheus集成:
监控缓存命中率、失效率、数据大小等。
应用场景:大规模分布式系统中缓存健康状态的实时监控。
这些高级功能让Ehcache不仅能服务于简单的缓存需求,还能作为复杂架构的重要组成部分。你可以根据具体业务需求设计相应的缓存方案,提升系统性能和用户体验。
5、总结
Ehcache 是一个功能强大且易于使用的缓存框架,通过简单的配置即可实现缓存管理。本文展示了如何通过 Maven 引入 Ehcache、手动配置缓存,以及集成 Spring Boot 使用缓存。
常见问题和优化建议:
- 缓存击穿:设置合理的缓存大小和过期时间,避免频繁访问同一失效数据。
- 缓存穿透:对缓存未命中的请求返回默认值,避免直接访问底层存储。
- 缓存雪崩:设置不同的缓存过期时间,避免同一时间大量缓存失效。
- 持久化存储:对重要数据开启磁盘持久化以防数据丢失。
希望这些内容能帮助您快速上手 Ehcache,提升系统性能!
评论区