RediStack: 适用于 Swift (iOS/macOS) 的异步 Redis 客户端
RediStack 是一个用 Swift 编写的现代、完全异步的 Redis 客户端。它基于高性能框架 SwiftNIO 构建,能够在不阻塞主线程的情况下高效处理网络请求。该库非常适合需要缓存、队列管理或 Pub/Sub 功能的 iOS 和 macOS 应用程序。
RediStack 支持所有主要的 Redis 功能:字符串、哈希、列表、集合、事务、管道 (pipeline) 以及发布/订阅 (Pub/Sub)。该库正在积极开发中,并得到 Swift 社区的支持。
安装
通过 Swift Package Manager 将 RediStack 添加到您的项目:
// Package.swiftdependencies: [ .package(url: "https://github.com/swift-server/RediStack.git", from: "1.0.0")],targets: [ .target(name: "MyApp", dependencies: ["RediStack"])]对于 CocoaPods,请使用:
pod 'RediStack', '~> 1.0'基本连接
使用 RedisConnection 创建到 Redis 服务器的连接:
import RediStackimport NIOCoreimport NIOPosix
let eventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: 1)let eventLoop = eventLoopGroup.next()
let connection = try await RedisConnection.connect( to: try .init(hostname: "localhost", port: 6379), on: eventLoop)数据操作
基本操作示例:
// 设置值try await connection.set("user:1:name", to: "阿列克谢")try await connection.set("user:1:age", to: 30)
// 获取值let name: String? = try await connection.get("user:1:name")print(name ?? "未找到") // 输出:阿列克谢
// 哈希操作try await connection.hset("user:1", field: "email", to: "alex@example.com")let email: String? = try await connection.hget("user:1", field: "email")
// 自增let newCount = try await connection.increment("page:views")print("浏览量:\\(newCount)")事务和管道
RediStack 支持管道,可一次性发送多个命令:
let pipeline = connection.pipeline()pipeline.set("key1", to: "value1")pipeline.set("key2", to: "value2")pipeline.get("key1")let results = try await pipeline.execute()// results — 按命令顺序返回的响应数组对于事务,请使用 MULTI/EXEC:
try await connection.sendCommandsImmediately(false)try await connection.set("balance", to: 100)try await connection.decrement("balance")try await connection.sendCommandsImmediately(true)Pub/Sub(发布和订阅)
RediStack 支持对频道进行异步订阅:
// 订阅频道let subscriber = connection.subscribe(to: "updates") { event in switch event { case .message(let channel, let message): print("从 \\(channel) 收到:\\(message)") default: break }}
// 发布消息try await connection.publish("大家好!", to: "updates")错误处理和重连
对于生产级应用程序,处理连接中断非常重要。RediStack 通过 RedisConnectionPool 提供重连机制:
let pool = RedisConnectionPool( configuration: .init( initialServerConnectionAddresses: [.init(hostname: "localhost", port: 6379)], maximumConnectionCount: .maximum(5) ), eventLoopGroup: eventLoopGroup)
// 像使用普通连接一样使用 pooltry await pool.set("session:token", to: "abc123")性能
得益于 SwiftNIO,RediStack 确保所有操作均非阻塞。这对于 iOS/mac