Browse Source

Support for Channel specification on ServiceClient

Adds support to allow consumers to specify a `Channel` when creating `ServiceClient` instances.

This is something already supported by other gRPC language flavors (like [Python](https://github.com/grpc/grpc/blob/7542ba6e0caee740f124dc25706287fd62f546d8/examples/python/multiplex/multiplex_client.py#L110)), and alleviates the need to create a new channel every time a call is made.

Usage:
```swift
let sharedChannel = Channel(address: "https://api.myservice.com", secure: true)
HelloWorldClient(channel: sharedChannel).getHelloWorld(...)
OtherClient(channel: sharedChannel).getOther(...)
```

Resolves https://github.com/grpc/grpc-swift/issues/200
Michael Rebello 7 years ago
parent
commit
bb6bd07cb5

+ 2 - 0
Sources/SwiftGRPC/Core/Channel.swift

@@ -41,6 +41,7 @@ public class Channel {
   /// - Parameter address: the address of the server to be called
   /// - Parameter secure: if true, use TLS
   public init(address: String, secure: Bool = true) {
+    gRPC.initialize()
     host = address
     if secure {
       underlyingChannel = cgrpc_channel_create_secure(address, roots_pem(), nil)
@@ -58,6 +59,7 @@ public class Channel {
   /// - Parameter certificates: a PEM representation of certificates to use
   /// - Parameter host: an optional hostname override
   public init(address: String, certificates: String, host: String?) {
+    gRPC.initialize()
     self.host = address
     underlyingChannel = cgrpc_channel_create_secure(address, certificates, host)
     completionQueue = CompletionQueue(

+ 7 - 0
Sources/SwiftGRPC/Runtime/ServiceClient.swift

@@ -55,6 +55,13 @@ open class ServiceClientBase: ServiceClient {
     metadata = Metadata()
   }
 
+  /// Create a client using a pre-defined channel.
+  public init(channel: Channel) {
+    gRPC.initialize()
+    self.channel = channel
+    self.metadata = Metadata()
+  }
+
   /// Create a client that makes secure connections with a custom certificate and (optional) hostname.
   public init(address: String, certificates: String, host: String?) {
     gRPC.initialize()