Kotlin 中的缓存:Redis、Caffeine 和 Ehcache — 完整指南

面向初学者的在线Python训练器

轻松学习Python,无需理论负担。在浏览器中直接解决带自动检查的实践任务,无需安装任何东西。

开始课程

Kotlin 中的缓存:Redis 及其他加速应用程序的工具



缓存是提高现代应用程序性能的关键机制之一。在 Kotlin(以及 Java)生态系统中,有多种强大的库可用于组织缓存:从简单的内存解决方案到基于 Redis 的分布式系统。在本文中,我们将介绍流行的工具、它们的配置以及在 Kotlin 语言中的使用示例。



为什么需要缓存?

缓存可以减少应用程序的响应时间,降低数据库和外部 API 的负载。主要场景包括:

  • 对相同数据的重复请求(例如,参考数据、设置);
  • 执行时间较长的计算(生成报告、复杂聚合);
  • 与外部服务交互(速率限制、网络延迟)。


1. Redis — 分布式缓存

Redis 是一种内存数据存储,通常用作分布式缓存。在 Kotlin/Java 生态系统中,主要客户端是 Lettuce 和 Jedis。对于 Spring Boot,推荐使用 spring-boot-starter-data-redis。



Redis 与 Kotlin 和 Spring Boot 集成示例

// build.gradle.ktsimplementation("org.springframework.boot:spring-boot-starter-data-redis")implementation("org.springframework.boot:spring-boot-starter-cache")

// application.ymlspring: cache: type: redis redis: host: localhost port: 6379

// 带缓存的服务@Serviceclass UserService(private val userRepository: UserRepository) {

@Cacheable("users") fun getUserById(id: Long): User { // 模拟长时间请求 Thread.sleep(2000) return userRepository.findById(id).orElseThrow() }

@CacheEvict("users", key = "#id") fun deleteUser(id: Long) { userRepository.deleteById(id) }}

@Cacheable 注解会自动将结果保存到 Redis,而 @CacheEvict 会在数据更改时删除记录。



2. Caffeine — 高性能内存缓存

Caffeine 是一个现代的本地缓存库,在速度和功能上显著优于 Guava Cache。它非常适合单线程或微服务架构。



在 Kotlin 中配置 Caffeine

// 依赖implementation("com.github.ben-manes.caffeine:caffeine:3.1.8")

// 创建缓存val cache: Cache<String, User> = Caffeine.newBuilder() .expireAfterWrite(10, TimeUnit.MINUTES) .maximumSize(1000) .recordStats() .build()

// 使用fun getUser(id: String): User { return cache.get(id) { key -> // 如果键不存在,则加载函数 userRepository.findById(key).orElseThrow() }}

// 获取统计信息println("Hit rate: ${cache.stats().hitRate()}")

Caffeine 支持自动过期旧条目(写入/访问后过期)、大小限制以及用于监控的统计信息收集。



3. Ehcache — 支持磁盘存储的成熟解决方案

Ehcache 是 Java 最古老的缓存库之一。它支持多层存储(堆内存、堆外内存、磁盘)和集群。对于 Kotlin,使用标准的 Java API。



Ehcache 3 与 XML 配置示例

// 依赖implementation("org.ehcache:ehcache:3.10.8")

// 配置 (ehcache.xml)<config xmlns="http://www.ehcache.org/v3"> <cache alias="users"> <key-type>java.lang.Long</key-type> <value-type>com.example.User</value-type> <resources> <heap unit="entries">100</heap> <offheap unit="MB">10</offheap> </res

推荐