当前位置:网站首页>Getting started with grpc swift

Getting started with grpc swift

2022-06-12 17:37:00 iOS Development

Put on a helmet first , All the following statements are not guaranteed to be correct , Please take it by yourself .

I don't want to see the bullshit in front of me , To go directly to the code , Please jump to 「iOS App How to implement and RPC Server communication 」 chapter

What is? RPC、gRPC、grpc-swift

Find out what is grpc-swift,

We must first figure out what is gRPC,

Find out what is gRPC,

We must first figure out what is RPC.

What is RPC

RPC, yes Remote procedure call For short , Translate it ——「 Remote procedure call 」.

Please speak in person ?OK, Take up a , If I want to transfer 1 A bitcoin for you ( In fact, I didn't 1 Bitcoin , Don't abandon Boca coin /Polkadot Words , I can transfer it to you —— It's been a terrible fall recently 🫠), Then I go through RPC such 「 transport 」 To you .

In essence, this is a process of data transmission . therefore RPC, It is simply understood as 「 A means of transmitting data 」.

Look at... In contrast , We have another more common way :HTTP+REST.( I don't know what ? It doesn't matter . It can be understood as another way to transmit data on the Internet .)

Simply speaking ,HTTP+REST The way , Focus on data data On : Send a request request, Then return the data response.

and RPC, Focus on 「 Method 」 On —— Call one directly 「 Method / function /command」—— It's just compared to calling methods inside the same software ,RPC Is a little different from the call in , It is from the computer A, Call the computer directly B One of the 「 Method 」, Is a remote call (Remote Call).

And then this 「 Method 」 And our common 「 Method 」 equally , There will be parameters 、 Return value . Data to transfer , Just put it in the parameter 、 In the return value , Finally realize the data transmission . Here's the picture :

RPC The data transmission process of

The source of the screenshot is : Comparing web API types: SOAP, REST, GraphQL and RPC

What is gRPC

OK,RPC Is a way to transmit data , that gRPC What is it again? ?

Smart you realize , There's one more here 「g」. however , Most people react first , Should not think that 「g」 It means 「Google」—— After all, baidu is the most useful search engine in the universe .

in fact 「g」 It means , It is Google( At least most people think so . About 「g」 Other meanings of , The following is a supplement ),gRPC yes Google The dominant pair RPC The concrete realization of . Selling point : High performance 、 Open source 、 Universal ( Support for many languages : Supported languages).

among ,Protocol Buffers, There is something you need to know . It can be compared to XML、JSON, however Protocol Buffers Smaller packets 、 Faster 、 Easier to implement .

As you might have guessed ,RPC also XML-RPC,JSON-RPC These other implementations . and gRPC, More accurate benchmarking , I think it should be called 「Protocol Buffers-RPC」~

Back to 「g」, in fact , Understand it as 「Google」 No mistake. , however , Engineers who often have nothing to do , Yes 「g」 There is another joke , details : GRPC Core: g_stands_for

In order to let everyone have a more intuitive understanding , Here is a part of the development history of Internet data transmission :

history

What is grpc-swift

OK, We have gRPC 了 , Is it possible to start writing iOS Terminal App, from 「RPC backstage 」 Got some data ? above-mentioned ,gRPC Support for multiple languages , Among them Objective-C( If you don't understand 「 Support 」 The meaning of , I will continue to explain later ).

however , Now we all use it Swift Development iOS App, So there it is grpc-swift 了 .

therefore , To sum up , Their relationship is as follows : ( by the way , Digression :Bitcoin It's using JSON-RPC

RPC The diagram

Why use gRPC

OK, Various concepts are mentioned above . that , Why use gRPC Well ? ( Be careful , My problem here is 「 Why use gRPC」, instead of 「 Why use RPC」)

Martial arts in the world , Fast break not only

This is an ancient motto that has been used for thousands of years .

gRPC Using the above mentioned Protocol Buffers, During data transmission , Data packets /payload It's based on binary /binary Of . therefore , Packet size, Than JSON Many small ( Imagine an example : One 55bytes, One 20bytes). in addition , Packets in binary form ,CPU Can be carried out more efficiently 「 serialize 」 and 「 Deserialization 」.

therefore , In a nutshell , use gRPC Little buddy , To squeeze out more performance .

Of course ,gRPC It's not a panacea , It also has its own disadvantages : Limited browser support 、 Binary format is not friendly to human beings and so on .

More pros and cons analysis , You can refer to : What is gRPC: Main Concepts, Pros and Cons, Use Cases

As for whether you want to use gRPC, Please think for yourself —— It doesn't seem to have anything to do with me .

iOS App How to implement and RPC Server communication

Okay , There's a lot of bullshit on it , It's finally the point .

Write a iOS Of App, and gRPC Back office communications . First , We need to have one gRPC backstage —— What a nonsense .

The server runs

Little friends without backstage experience don't need chrysanthemum , You just need to type in at your terminal swift run HelloWorldServer This line of command , Then tap the Enter key again , official GitHub Of HelloWorld backstage , It will run miraculously :

  • hold grpc-swift project clon Come down
  • cd To the project root directory
  • Open the terminal /Termanil, perform swift run HelloWorldServer command ( After success, you will see the printing of the terminal :server started on port 1234

such ,RPC The backstage started running . What data can you get from this background ? First, there is a method in the background sayHello() Available (App) Client calls , then , Suppose you call this method and pass in Antony As a parameter of the method ( To be exact, it should be a Rquest object ), He will return the string Hello Antony!( To be exact, it should be a Response object ). If parameters are not passed , Default return Hello stranger!. It's not very good ?!

If you can't wait , Didn't write well App, Just want to adjust sayHello() Try the method . Sure :

  • Open another terminal
  • cd To the project root directory
  • perform swift run HelloWorldClient command ( After success, you will see the print :Greeter received: Hello stranger!) Represents our client ( Is a command line tool ) Called sayHello() And received the data from the background server !

RPC Running backstage !

.proto Writing of documents

Writing App Before , I would also like to introduce .proto file .

It says , Our client side , Called sayHello() Method , similarly , And then we'll have App, This method will also be called , get data , And this method naturally uses Swift Written language , Do we need to write this method ourselves ? The answer is no need for . Where does this method come from ?

The answer is what follows .proto file . We make use of Protocol Buffers This Interface description language , To put our data transmission process 「 Data model 」 and 「 Method 」 stay .proto The file defines , Then pass the relevant instructions , Generate the code your client needs . such as iOS Of Swift、Android Of Kotlin wait . ( That's what it says 「gRPC Support for multiple languages 」, That's what it means .)

Here are the... In the warehouse helloworld.proto file

// Protocol Buffers Yes proto2 edition , This shows , We use a relatively new one proto3 edition 
syntax = "proto3";

//  Below option, Some configurations during code generation 
option java_multiple_files = true; //  Generated Java Code , Whether to divide into multiple files 
option java_package = "io.grpc.examples.helloworld";
option java_outer_classname = "HelloWorldProto";
option objc_class_prefix = "HLW"; //  Generated Objective-C What is the prefix of the code 

// 「 Package name 」. Imagine , You define it here 、 Last generated 「 class 」 and 「 Method 」, It may be different from your original App Of 「 class 」、「 Method 」 The nuptial .
//  Let's add one here package The name of , avoid 「 name conflict 」
package helloworld;

//  Define a service
//  In fact, you can be in the same  .proto file , Define multiple serive( According to my current understanding , Doing so allows for different functions APIs, More organized ?)
service Greeter {
  // SayHello Specific definition of interface method 
  rpc SayHello (HelloRequest) returns (HelloReply) {}
}

//  Parameters HelloRequest The definition of 
//  Be careful , there 1, It's not for name assignment , It's a sign tag, Field matching for serialization and deserialization 
//  there message keyword , It can be understood as and class similar 
message HelloRequest {
  string name = 1;
}

//  return type HelloReply The definition of 
message HelloReply {
  string message = 1;
}

//  If there are other data models and methods , Just keep adding . Isn't it quite simple ?

Specific grammar introduction : Language Guide (proto3)

There's a little bit of clarification here , .proto file , In theory, it was written by the Engineer in charge of the backstage . Maybe it's more nice A little colleague , Will generate swift Here you are , You can use it directly . Not so nice Of , May put .proto The file is lost to you , Let yourself play .

But the best practices here , I believe it is the front and rear engineers who discuss .proto In file API Interface writing , After all, there are differences between front and back-end development , It's hard to avoid writing something that doesn't meet the other person's expectations API Interface .

Interested front-end partners , You can also try to helloworld.proto Adding points to files , Change something , Regenerate code , Update implementation . Feel the background development .

Generation of interface code

OK, Now we have .proto The file , If we meet someone who is not so nice My backstage colleagues , hold .proto The file is thrown directly , How to generate Swift Code ?

gRPC Swift A plug-in is provided /plugin, It's called protoc( The name is bad enough ? Make people very confusing). See : protoc gRPC Swift plugin ( If you do not install the plug-in and run the generated code instructions , Report errors command not found: protoc

Plug in installation , If it is macOS( No one should use Windows do iOS Developed ?), Execute commands directly at the terminal brew install swift-protobuf grpc-swift, use Homebrew To install . More detailed installation instructions :Getting the protoc Plugins

( There's a pit here , At first I found gRPC Official website installation tutorial Protocol Buffer Compiler Installation, This is not aimed at Swift Of , You will be prompted when generating code after installation protoc-gen-grpc-swift: program not found or is not executable

After installation , You can use the command to generate Swift Code. . however , Let's see what the generated code file looks like :

Generated Swift Files

You can see , Two documents ( The naming is a little strange ):

  • .grpc.swift The file generated is :API Interface method ( Corresponding to the above SayHello Method )、Client(App End use )、Provider( It is used in the background —— For backstage engineers )
  • .pb.swift The file generated is : Model class ( Corresponding to the above HelloRequest,HelloReply

next , You can click the command line to generate code , Personally, the command line is still a little complicated , Knock for a long time , To understand , So draw a picture to illustrate ( With This directory Under the helloworld.proto File as an example . First cd To the root directory of the warehouse grpc-swift):

Code generation instruction description

After executing the above order , If no accident , Will get helloworld.grpc.swift and helloworld.pb.swift Two documents .

May refer to : protoc gRPC Swift plugin—— But I haven't explained it clearly yet

App End request data

Finally I can write App The end of the code !!!

Create a new one iOS engineering , obtain gRPC Swift: It can be used Swift Package Manager; You can import... Manually ; It can also be used. CocoaPods. Details can be found in Github The warehouse README.

Connect to server , Calling method , get data

Then you can connect gRPC The server is up and getting the data :

let group = PlatformSupport.makeEventLoopGroup(loopCount: 1)

//  Create a channel
//  adopt host and port, You will know to connect to the server 
let channel = try? GRPCChannelPool.with(target: .host("localhost", port: 1234),
                                        transportSecurity: .plaintext,
                                        eventLoopGroup: group)

//  establish Client object 
// Helloworld_GreeterClient It's based on .proto File generated code 
let greeter = Helloworld_GreeterClient(channel: channel!)

//  establish Request object , Pass it to the server as a parameter of the method 
let request = Helloworld_HelloRequest.with {
    $0.name = "ANTONY"
}

//  Pass in the parameter , Calling method 
let sayHello = greeter.sayHello(request)

do {
    //  Get the return value of the method ( Data returned in the background )
    let response = try sayHello.response.wait()
    print("Greeter received: \(response.message)")
} catch {
    print("Greeter failed: \(error)")
}

You'll see in the end Xcode Console printing :Greeter received: Hello ANTONY!. So it's done gRPC「 client 」 and 「 The server 」 Data transmission between .

Are you kidding me? Just a few lines of code ? You wrote 3000 word ?

OK, take it easy , Later, I will write something more advanced .

原网站

版权声明
本文为[iOS Development]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/163/202206121731439496.html