当前位置:网站首页>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
, performswift 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 ) CalledsayHello()
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 aboveSayHello
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 aboveHelloRequest
,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 .
边栏推荐
- Yyds dry goods inventory leetcode question set 911 - 920
- 三代DRI的变化
- Tcp/ip family structure and protocol of tcp/ip series overview
- ftrace
- Microsoft Office MSDT Code Execution Vulnerability (cve-2022-30190) vulnerability recurrence
- Basic knowledge of stock introduction: is fixed increase good or bad?
- (7) Loop statement for
- [BSP video tutorial] stm32h7 video tutorial Issue 8: the last issue of the MDK theme, the new generation of debugging technologies event recorder and RTT, and using stm32cubemx to generate project tem
- Codeforces Round #398 (Div. 2) D. Cartons of milk
- Record the use of yolov5 to detect rotating targets
猜你喜欢
"Upgrade strategy" of two new committers
To understand Devops, you must read these ten books!
LCD参数解释及计算
Modify the configuration of the router connected to your computer. The website is 192.168.1.1
Guitar Pro tutorial how to set up a MIDI keyboard
JDBC几个坑
Arm64 Stack backtrack
Fiddler抓包几种常用功能介绍(停止抓包、清空会话窗内容、过滤请求、解码、设置断点......)
WinForm, crystal report making
Yyds dry goods inventory leetcode question set 911 - 920
随机推荐
php 实现无限极分类树(递归及其优化)
MySQL authorization summary
First acquaintance with go language
Basic knowledge of stock introduction: is fixed increase good or bad?
Tensorflow reads data from the network
(8) Goto keyword
Kill program errors in the cradle with spotbugs
Second week of electric control learning
进阶之大山-asp.net core 路由程序基础使用演示0.1
Operating with idle funds
Goframe gredis configuration management | comparison of configuration files and configuration methods
To understand Devops, you must read these ten books!
Introduction of one object one code tracing system
分辨率与行场同步信号的关系 场消隐
系统设计之图状数据模型
R语言使用epiDisplay包的summ函数计算dataframe中指定变量在不同分组变量下的描述性统计汇总信息并可视化有序点图(名称、有效值个数、均值、中位数、标准差、最大值、最小值)
R语言使用epiDisplay包的tableStack函数基于分组变量生成统计分析表(包含描述性统计分析、假设检验、不同数据使用不同的统计量和假设检验方法)、自定义配置是否显示统计检验内容
Gerrit triggers Jenkins sonarqube scan
卖疯了的临期产品:超低价、大混战与新希望
1723. minimum time to complete all work