柚子快報邀請碼778899分享:后端 Rust使用gRPC
柚子快報邀請碼778899分享:后端 Rust使用gRPC
需要先安裝protoc(Protocol Buffers Compiler),可據(jù)此Protobuf Compiler Installation下載
第一步:創(chuàng)建項目
創(chuàng)建兩個新的Rust項目,分別作為服務(wù)端與客戶端:
cargo?new?rust_grpc_servercargo?new?rust_grpc_client
分別在項目根目錄創(chuàng)建proto文件夾,并在其中創(chuàng)建一個叫hello.proto的文件
第二步:編寫.proto文件
在proto/hello.proto文件中分別寫入以下內(nèi)容:
syntax = "proto3";
package hello;
// The greeting service definition.
service Greeter {
// Sends a greeting
rpc SayHello (HelloRequest) returns (HelloReply) {}
}
// The request message containing the user's name.
message HelloRequest {
string name = 1;
}
// The response message containing the greetings.
message HelloReply {
string message = 1;
}
第三步:添加依賴
在server的項目的Cargo.toml文件中添加以下依賴:
[dependencies]
tonic = "0.6"
tokio = { version = "1", features = ["full"] }
prost = "0.9"
[build-dependencies]
tonic-build = "0.6"
在client的項目的Cargo.toml文件中添加以下依賴:
[dependencies]tonic?=?"0.6"tokio?=?{?version?=?"1",?features?=?["full"]?}prost?=?"0.9"rand?=?"0.8"[build-dependencies]tonic-build?=?"0.6"
第四步:創(chuàng)建build腳本
分別在根目錄創(chuàng)建一個build.rs文件,添加以下代碼, 根據(jù).proto文件生成相應(yīng)的Rust代碼:
fn?main()?{????tonic_build::compile_protos("proto/hello.proto")????????.expect("Failed?to?compile?proto?files");}
最終生成的代碼類似
第五步:編寫gRPC服務(wù)器
在server項目的src/main.rs中,創(chuàng)建一個gRPC服務(wù)器:
use?std::time::SystemTime;use?tonic::{transport::Server,?Request,?Response,?Status};pub?mod?hello?{????tonic::include_proto!("hello");}use?hello::greeter_server::{Greeter,?GreeterServer};use?hello::{HelloReply,?HelloRequest};#[derive(Default)]pub?struct?MyGreeter?{}#[tonic::async_trait]impl?Greeter?for?MyGreeter?{????async?fn?say_hello(????????&self,????????request:?Request
第六步:編寫gRPC客戶端
在client項目的src/main.rs文件中,添加一個客戶端來測試服務(wù)器:
use?rand::Rng;pub?mod?hello?{????tonic::include_proto!("hello");}use?hello::HelloRequest;#[derive(Default)]pub?struct?MyGreeter?{}//?客戶端代碼#[tokio::main]async?fn?main()?->?Result<(),?Box
編譯和運行
在server項目根目錄執(zhí)行
cargo run來編譯和運行項目,服務(wù)器將啟動并監(jiān)聽在
[::1]:50051
在client項目根目錄執(zhí)行
cargo run來編譯和運行項目,客戶端將發(fā)送一個請求并打印出服務(wù)端的響應(yīng)內(nèi)容
本文由 mdnice 多平臺發(fā)布
柚子快報邀請碼778899分享:后端 Rust使用gRPC
好文推薦
本文內(nèi)容根據(jù)網(wǎng)絡(luò)資料整理,出于傳遞更多信息之目的,不代表金鑰匙跨境贊同其觀點和立場。
轉(zhuǎn)載請注明,如有侵權(quán),聯(lián)系刪除。