SuperAPI AI 工具集

valkey

数据与分析

查看项目

更新于 10-16 07:01

技能介绍

用途

本技能用于在 Swift 开发中提供 Valkey 与 Redis 使用方面的专业指导。当开发者提及以下内容时可使用:Valkey 或 Redis 在 Swift 中的使用、valkey-swift 库、RESP 协议等。

主要能力

快速开始

在 Package.swift 中添加依赖:

dependencies: [
    .package(url: "https://github.com/valkey-io/valkey-swift.git", from: "1.0.0")
]

基础用法:

import Valkey

// Connect to single server
let client = try await ValkeyClient.connect(to: .init(host: "localhost", port: 6379))

// Basic operations
try await client.set("key", "value")
let value = try await client.get("key") // Optional<String>

// With expiration
try await client.set("session", sessionData, expiration: .seconds(3600))

// Delete
try await client.del("key")

集群模式

// Connect to cluster
let client = try await ValkeyClient.connect(
    to: .cluster([
        .init(host: "node1.redis.local", port: 6379),
        .init(host: "node2.redis.local", port: 6379),
        .init(host: "node3.redis.local", port: 6379)
    ])
)

// Commands automatically route to correct shard
try await client.set("user:123", userData)

命令

字符串:

// SET with options
try await client.set("key", "value", condition: .nx)  // Only if not exists
try await client.set("key", "value", condition: .xx)  // Only if exists
try await client.set("key", "value", expiration: .milliseconds(5000))

// GET
let value = try await client.get("key")

// INCR/DECR
let newValue = try await client.incr("counter")
let decreased = try await client.decr("counter")
try await client.incrBy("counter", 10)

哈希:

try await client.hset("user:123", field: "name", value: "Alice")
try await client.hset("user:123", fields: ["name": "Alice", "email": "alice@example.com"])

let name = try await client.hget("user:123", field: "name")
let user = try await client.hgetall("user:123") // [String: String]

列表:

try await client.lpush("queue", "item1", "item2")
try await client.rpush("queue", "item3")

let item = try await client.lpop("queue")
let items = try await client.lrange("queue", start: 0, stop: -1)

集合:

try await client.sadd("tags", "swift", "redis", "backend")
let isMember = try await client.sismember("tags", "swift")
let members = try await client.smembers("tags")

有序集合:

try await client.zadd("leaderboard", score: 100, member: "player1")
try await client.zadd("leaderboard", members: [("player2", 200), ("player3", 150)])

let top10 = try await client.zrange("leaderboard", start: 0, stop: 9, withScores: true)
let rank = try await client.zrank("leaderboard", member: "player1")

发布/订阅

// Subscribe to channels
let subscription = try await client.subscribe(to: ["notifications", "updates"])

// Process messages
for try await message in subscription {
    switch message {
    case .message(let channel, let payload):
        print("Received on \(channel): \(payload)")
    case .subscribe(let channel, let count):
        print("Subscribed to \(channel)")
    }
}

// Publish
try await client.publish("notifications", message: "Hello subscribers!")

// Pattern subscribe
let patternSub = try await client.psubscribe(to: ["user:*", "event:*"])

事务

// MULTI/EXEC transaction
let results = try await client.transaction(
    SET("key1", "value1"),
    SET("key2", "value2"),
    GET("key1")
)
// Results is tuple: (Result<String?, Error>, Result<String?, Error>, Result<String?, Error>)

流水线

// Execute multiple commands in single round-trip
let (setResult, getResult, incrResult) = try await client.execute(
    SET("key", "value"),
    GET("key"),
    INCR("counter")
)

集群路由

命令会根据键哈希槽自动路由至正确的分片:

// Keys with same hash tag go to same shard
try await client.set("{user:123}:profile", profileData)
try await client.set("{user:123}:settings", settingsData)
// Both keys route to same shard due to {user:123} hash tag

连接配置

let config = ValkeyClient.Configuration(
    endpoints: .single(.init(host: "localhost", port: 6379)),
    password: "secret",
    database: 0,
    connectionTimeout: .seconds(5),
    commandTimeout: .seconds(30),
    tls: .require(.makeClientConfiguration())
)

let client = try await ValkeyClient.connect(configuration: config)

错误处理

do {
    let value = try await client.get("key")
} catch let error as ValkeyClientError {
    switch error {
    case .connectionClosed:
        // Reconnect logic
    case .timeout:
        // Retry logic
    case .serverError(let message):
        print("Server error: \(message)")
    }
}

参考文件

按需加载以下文件以获取特定主题内容:

  • references/valkey-patterns.md - 命令协议模式、RESP 编解码、基于哈希槽的集群路由、订阅管理、事务模式、连接池集成、模块扩展

使用方式

在 Swift 项目中通过 Package.swift 添加 valkey-swift 依赖,导入 Valkey 模块后创建客户端实例,即可调用异步 API 执行键值操作、发布订阅、事务和流水线等命令。

适用场景

  • 需要在 Swift 应用中接入 Valkey 或 Redis 作为键值存储
  • 需要利用 async/await 进行异步数据访问
  • 需要连接单机或集群模式的 Valkey/Redis 服务
  • 需要使用发布订阅、事务、流水线或集群哈希槽路由等特性

限制

关于收费、价格、平台支持范围、性能指标等信息,资料中暂未提供。