SwiftEureka

Build Package GitHub license GitHub Releases GitHub Issues

用于 netflix/spring Eureka 的 Swift 库

这是一个设计上很简单的 Eureka 客户端包。未实现服务器轮询,也未实现缓存等功能。

该包为公共 API 使用了 async/await

创建 InstanceInfo 并使用 EurekaClient 向 Eureka 注册实例的示例

API

初始化 (Init)

要初始化 EurekaClient 的实例,我们需要传入 Eureka 服务器的 URL,并可选择性地提供一个 Logger。如果提供了 Logger,则 EurekaClient 将使用它来记录服务调用信息。如果未提供 logger,则不会记录任何内容(正如您所期望的那样)。

我们目前使用 swift-log 包进行日志记录。

let client = EurekaClient(
    baseUrl: URL(string: "http://192.168.0.88:8761")!, 
    logger: Logger(label: "com.putridparrot.MyApp"))

注册 (Register)

要向 Eureka 注册您的应用程序,请使用以下 register 方法,并传入您应用程序的 InstanceInfo

var instance = InstanceInfo()
instance.hostName = "myhost"
instance.app = "SWIFT-EUREKA"
instance.vipAddress = "myservice"
instance.secureVipAddress = "myservice"
instance.ipAddr = "10.0.0.10"
instance.status = InstanceStatus.up
instance.port = Port(number: 8080, enabled: true)
instance.securePort = Port(number: 8443, enabled: true)
instance.healthCheckUrl = "http://myservice:8080/healthcheck"
instance.statusPageUrl = "http://myservice:8080/status"
instance.homePageUrl = "http://myservice:8080"

do {
    try await client.register(instanceInfo: instance)
}
catch {
   print("Unexpected error \(error)")
}

注销 (Unregister)

要注销并从 Eureka 中删除您应用程序的详细信息,请使用 unregister 方法。您需要传入使用 instance.app 在您的 InstanceInfo 中注册的 appId。以及每个 instance.hostName 的特定 instanceId

do {
    try await client.unregister(appId: "SWIFT-EUREKA", instanceId: "myhost")
}
catch {
   print("Unexpected error \(error)")
}

findAll

如果您的应用程序需要调用 Eureka 服务器并获取已注册应用程序的数组,请使用 findAll。这将返回已注册的应用程序名称以及它们的所有实例信息。

do {
    let applications = try await client.findAll()

    print("List of Applications")
    for application in applications!.application {
        print(application.name)
    }}
catch {
   print("Unexpected error \(error)")
}

返回值为 Applications 类型,其中包含一些 Eureka 特定的信息以及 _Application_ 类型的数组。Application 类型包括应用程序名称和已注册的 InstanceInfo 数组(针对该应用程序名称)。

find

在大多数情况下,希望在 Eureka 中查找实例的应用程序只需按 appIdappIdinstanceId 查找。find 方法允许我们做到这一点。

do {
    let application = try await client.find(appId)
}
catch {
   print("Unexpected error \(error)")
}

sendHeartBeat

向 Eureka 发送心跳

do {
    try await client.sendHeartBeat(appId: "SWIFT-EUREKA", instanceId: "myhost")
}
catch {
   print("Unexpected error \(error)")
}

takeOutOfService

将您的服务标记为“停止服务”

do {
    try await client.takeOutOfService(appId: "SWIFT-EUREKA", instanceId: "myhost")
}
catch {
   print("Unexpected error \(error)")
}

moveInstanceIntoService

将您的服务标记为“运行中”,使其恢复服务

do {
    try await client.moveInstanceIntoService(appId: "SWIFT-EUREKA", instanceId: "myhost")
}
catch {
   print("Unexpected error \(error)")
}