一个维护良好的 Swift 客户端,用于基于 NIO2 与 nats 服务器进行交互。
加入 nats.io Slack 上的 #swift 频道。我们将尽最大努力快速提供帮助。您也可以顺道来打个招呼。我们期待发展社区。
将此软件包作为依赖项添加到您的项目的 Package.swift
文件中,并将名称添加到您的目标,如本示例所示
// swift-tools-version:5.4
import PackageDescription
let package = Package(
name: "YourApp",
products: [
.executable(name: "YourApp", targets: ["YourApp"]),
],
dependencies: [
.package(name: "SwiftyNats", url: "https://github.com/aus-der-technik/SwiftyNats.git", from: "2.2.0")
],
targets: [
.target(
name: "YourApp",
dependencies: ["SwiftyNats"]
),
]
)
在 XCode 中打开项目检查器并选择您的项目。重要的是选择项目而不是目标!单击第三个选项卡 Package Dependencies
并添加 git URL https://github.com/aus-der-technik/SwiftyNats.git
,方法是选择包列表末尾的小 +
符号。
import SwiftyNats
// register a new client
let client = NatsClient("http://nats.server:4222")
// listen to an event
client.on(.connect) { _ in
print("Client connected")
}
// try to connect to the server
try? client.connect()
// subscribe to a channel with a inline message handler.
client.subscribe("foo.bar") { message in
print("payload: \(message.payload)")
print("size: \(message.byteCount)")
print("reply subject: \(message.replySubject.subject)")
}
// publish an event onto the message strem into a subject
client.publish("this event happened", to: "foo.bar")
默认日志级别为 .error
。您可以重置它以查看更详细的消息。可能的值为 .debug
、.info
、.error
或 .critical
let client = NatsClient("http://nats.server:4222")
client.config.loglevel = .info
重新连接不是此软件包的一部分,因为如果服务器断开连接,您的应用程序必须确保再次正确建立订阅。
使用 SwiftyNats,这是一个非常简单的步骤
// register a new client
let client = NatsClient(url)
// listen to the .disconnected event to try a reconnect
client.on(.disconnected) { [self] _ in
sleep(5);
try? client.reconnect()
doSubscribe()
}
// subscribe to the channels
doSubscribe()
// private function to subscribe to channels
private func doSubscribe(){
client.subscribe("foo.bar") { message in
print("payload: \(message.payload)")
}
}
公共类 NatsEvent
包含您可以订阅的所有事件。
事件 | 描述 |
---|---|
已连接 | 客户端已连接到服务器。 |
已断开连接 | 客户端断开连接,并且之前已连接。 |
响应 | 客户端从服务器获取响应(内部)。 |
错误 | 服务器发送无法处理的错误。 |
已丢弃 | 客户端丢弃了一条消息。主要是因为队列长度太短。 |
正在重新连接 | 客户端正在重新连接到服务器(因为调用了 reconnect())。 |
已通知 | 服务器已成功将其信息数据发送到客户端。 |
自 2.0.2 起,可以从连接的服务器获取信息
let client = NatsClient("http://nats.server:4222")
print("\(client.serverInformation.serverName) has Version: \(client.serverInformation.version))");
随时欢迎贡献。只需给我发送一个 pull request。
参见:贡献 ;)