Kotlin 的 Redis 客户端:Lettuce 与 Kreds 对比及示例

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

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

开始课程

Kotlin 的 Redis 客户端:流行库概览与对比



Redis 是一种高性能的键值存储数据库,广泛用于缓存、会话、队列和实时应用。对于 Kotlin 语言,有多个成熟的客户端可以高效地与 Redis 交互。在本文中,我们将介绍两个主要的库:Lettuce(异步、非阻塞)和 Kreds(专为 Kotlin 设计,支持协程)。



1. Lettuce — 强大且灵活的 JVM 客户端



Lettuce 是一个基于 Java 的异步 Redis 客户端,在 Kotlin 项目中也能很好地工作。它支持同步、异步(基于 CompletableFuture)和响应式(Project Reactor / RxJava)API。Lettuce 是 Spring Boot 和微服务中最流行的解决方案之一。



依赖配置 (Gradle)

dependencies {    implementation("io.lettuce:lettuce-core:6.3.2.RELEASE")}


同步连接与操作示例

import io.lettuce.core.RedisClientimport io.lettuce.core.api.sync.RedisCommands

fun main() { val client = RedisClient.create("redis://localhost:6379") val connection = client.connect() val commands: RedisCommands<String, String> = connection.sync()

// 设置和获取值 commands.set("mykey", "Hello from Lettuce!") val value = commands.get("mykey") println("Value: $value") // Hello from Lettuce!

// 哈希操作 commands.hset("user:1", "name", "Alice") commands.hset("user:1", "age", "30") val name = commands.hget("user:1", "name") println("User name: $name")

connection.close() client.shutdown()}


使用协程的异步模式

Lettuce 通过 CompletableFuture 支持异步 API,可以轻松地通过 await() 适配 Kotlin 协程:

import kotlinx.coroutines.runBlockingimport kotlinx.coroutines.future.await

fun main() = runBlocking { val client = RedisClient.create("redis://localhost:6379") val connection = client.connect() val asyncCommands = connection.async()

val result = asyncCommands.set("coroutine-key", "Kotlin + Lettuce").await() println("Set result: $result")

val value = asyncCommands.get("coroutine-key").await() println("Value: $value")

connection.close() client.shutdown()}


2. Kreds — 以 Kotlin 为先的协程客户端



Kreds 是一个完全用 Kotlin 编写的现代 Redis 客户端。它原生支持协程、Flow 和通过 kotlinx.serialization 进行的序列化。Kreds 底层使用 Netty,但提供了纯粹的 Kotlin API。



依赖配置 (Gradle)

dependencies {    implementation("io.ktor:kreds:0.9.0")}


基本使用示例

import io.kreds.client.RedisClient

suspend fun main() { val client = RedisClient("localhost", 6379)

client.set("kreds-key", "Hello from Kreds!") val value = client.get("kreds-key") println("Value: $value")

// 列表操作 client.lpush("mylist", "A", "B", "C") val item = client.rpop("mylist") println("Popped: $item")

client.close()}


使用 Flow 订阅频道

Kreds 通过 Kotlin Flow 支持发布/订阅模式,非常适合响应式应用:

import io.kreds.client.RedisClientimport kotlinx.coroutines.flow.collect

suspend fun main() { val client = RedisClient("localhost", 6379)

client.subscribe("channel-1").collect { message -> println("Received: ${message.payload}") }}


3. Lettuce 与 Kreds 对比



推荐

特性