RediStack:适用于 Swift (iOS/macOS) 的异步 Redis 客户端
RediStack 是一个用 Swift 编写的现代化、完全异步的 Redis 客户端库。该库基于 SwiftNIO 框架构建,具有高性能和低内存消耗的特点。RediStack 非常适合需要快速缓存、会话管理、消息队列或 Pub/Sub 功能的 iOS 和 macOS 应用程序。
主要功能
- 基于 Swift Concurrency (async/await) 和 Combine 的完全异步支持
- 支持所有主要的 Redis 数据类型:字符串、列表、集合、哈希、流
- 内置 Pub/Sub 支持,并具备自动重连功能
- 自动连接池管理 (Connection Pool)
- 支持 Redis Cluster 和 Sentinel
- SSL/TLS 加密,确保安全连接
- 类型安全的命令,在 Xcode 中支持自动补全
使用 Swift Package Manager 安装
将 RediStack 添加到您的 Package.swift 或通过 Xcode 添加:
// Package.swiftdependencies: [ .package(url: "https://github.com/RediStack/RediStack.git", from: "1.6.0")],targets: [ .target(name: "YourApp", dependencies: ["RediStack"])]快速入门:连接到 Redis
首先,创建一个连接池并执行简单命令:
import RediStackimport NIO
// 创建 EventLoopGrouplet eventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: 1)
// 配置连接池let pool = RedisConnectionPool( configuration: .init( initialServerConnectionAddresses: [try .init(hostname: "localhost", port: 6379)], maximumConnectionCount: .maximumActiveConnections(5) ), boundEventLoop: eventLoopGroup.next())
// 异步操作 RedisTask { do { // 设置和获取字符串 try await pool.set("greeting", to: "Hello from Swift!") let value = try await pool.get("greeting", as: String.self) print("获取的值: \\(value ?? "nil")") // "获取的值: Hello from Swift!" // 操作列表 try await pool.lpush(["apple", "banana", "cherry"], into: "fruits") let fruits = try await pool.lrange(from: "fruits", firstIndex: 0, lastIndex: -1, as: [String].self) print("水果: \\(fruits)") // ["cherry", "banana", "apple"] } catch { print("Redis 错误: \\(error)") }}示例:Pub/Sub(发布-订阅)
RediStack 支持完整的 Pub/Sub 功能,并具备自动恢复订阅的能力:
import RediStackimport NIO
let eventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: 2)let pool = RedisConnectionPool(...)
// 订阅者Task { let subscriber = pool.makeSubscriber(eventLoop: eventLoopGroup.next()) // 订阅频道 await subscriber.subscribe(to: "notifications") { channel, message in print("在频道 \\(channel) 上收到消息: \\(message.string ?? "")") } // 处理订阅错误 subscriber.onError = { error in print("Pub/Sub 错误: \\(error)") }}
// 发布者(发送消息)Task { try await pool.publish("新通知", to: "notifications")}操作哈希和事务
使用哈希和事务进行原子操作的示例:
// 设置哈希字段try await pool.hmset("user:1001", with: [ "name": "伊万·彼得罗夫", "email": "ivan@example.com", "age": "30"])
// 获取所有字段let user = try await pool.hgetall(from: "user:1001")print("姓名: \\(user["name"]?.string ?? "")") // "姓名: 伊万·彼得罗夫"
// 事务(原子执行)try await pool.transaction { transaction in transaction.inc