0
点赞
收藏
分享

微信扫一扫

012 Rust 网络编程,gRPC 演示示例


演示说明

本例子的功能为grpc客户端向服务端写入位置信息和读取位置信息,演示环境为ubuntu。

准备工作

安装protobuf编译器:

apt install protobuf-compiler

演示实例

新建工程

cargo new use_grpc --lib #记住这个名字use_grpc,因为在编写代码的时候要用

新建proto文件

在use_grpc目录下,创建foobar.proto文件,编写代码如下:

syntax = "proto3";

package foobar;

service FooBarService {
rpc record_cab_location(CabLocationRequest) returns (CabLocationResponse);
rpc get_cabs(GetCabRequest) returns (GetCabResponse);
}

message CabLocationRequest {
string name = 1;
Location location = 2;
}

message CabLocationResponse {
bool accepted = 1;
}

message GetCabRequest {
Location location = 1;
}

message GetCabResponse {
repeated Cab cabs = 1;
}

message Cab {
string name = 1;
Location location = 2;
}

message Location {
float latitude = 1;
float longitude = 2;
}

创建构建脚本

在use_grpc目录下,创建build.rs文件,编辑如下:

extern crate protoc_rust_grpc;

fn main() {
protoc_rust_grpc::Codegen::new()
.out_dir("src")
.input("foobar.proto")
.rust_protobuf(true)
.run()
.expect("protoc-rust-grpc");
}

编写Cargo.toml文件

在文件中添加如下内容:

[dependencies]
protobuf = "2"
grpc = "0.7.1"
grpc-protobuf = "0.7.1"
futures = "0.3.*"
tls-api = "0.3.*"

[build-dependencies]
protoc-rust-grpc = "0.7.1"

[[bin]]
name = "client"
test = false

[[bin]]
name = "server"
test = false

编写源码

编写lib.rs

编写src目录下lib.rs,如下:

pub mod foobar;
pub mod foobar_grpc;

编写服务端

在src目录下创建bin目录,在bin目录中创建server.rs,编写如下:

use std::thread;

use use_grpc::foobar_grpc::*;//use_grpc为当前包的名字,如果名字不一样需要修改
use use_grpc::foobar::*;//use_grpc为当前包的名字,如果名字不一样需要修改

struct FooBarServer;

impl FooBarService for FooBarServer {
fn record_cab_location(&self,
_o: grpc::ServerHandlerContext,
req: grpc::ServerRequestSingle<CabLocationRequest>,
resp: grpc::ServerResponseUnarySink<CabLocationResponse>)
-> grpc::Result<()>
{
let mut r = CabLocationResponse::new();

println!("Recorded cab {} at {}, {}", req.message.get_name(), req.message.get_location().latitude, req.message.get_location().longitude);

r.set_accepted(true);
resp.finish(r)
}

fn get_cabs(&self,
_o: grpc::ServerHandlerContext,
_req: grpc::ServerRequestSingle<GetCabRequest>,
resp: grpc::ServerResponseUnarySink<GetCabResponse>)
-> ::grpc::Result<()>
{
let mut r = GetCabResponse::new();

let mut location = Location::new();
location.latitude = 40.7128;
location.longitude = -74.0060;

let mut one = Cab::new();
one.set_name("Limo".to_owned());
one.set_location(location.clone());

let mut two = Cab::new();
two.set_name("Merc".to_owned());
two.set_location(location.clone());

let vec = vec![one, two];
let cabs = ::protobuf::RepeatedField::from_vec(vec);

r.set_cabs(cabs);

resp.finish(r)
}
}

fn main() {
let mut server = grpc::ServerBuilder::new_plain();
server.http.set_port(9001);
server.add_service(FooBarServiceServer::new_service_def(FooBarServer));
// server.http.set_cpu_pool_threads(4);
let _server = server.build().expect("Could not start server");
loop {
thread::park();
}
}

编写客户端

在src/bin目录下创建client.rs,编写如下:

use use_grpc::foobar::*;//use_grpc为当前包的名字,如果名字不一样需要修改
use use_grpc::foobar_grpc::*;//use_grpc为当前包的名字,如果名字不一样需要修改
use futures::executor;

use grpc::ClientStubExt;


fn main() {
let client =
FooBarServiceClient::new_plain("127.0.0.1",
9001,
Default::default())
.unwrap();

let mut req = CabLocationRequest::new();
req.set_name("foo".to_string());

let mut location = Location::new();
location.latitude = 40.730610;
location.longitude = -73.935242;
req.set_location(location);

let resp = client
.record_cab_location(grpc::RequestOptions::new(), req)
.join_metadata_result();
let resp = executor::block_on(resp);
match resp {
Err(e) => panic!("{:?}", e),
Ok((_, r, _)) => println!("{:?}", r),
}

let mut nearby_req = GetCabRequest::new();
let mut location = Location::new();
location.latitude = 40.730610;
location.longitude = -73.935242;
nearby_req.set_location(location);

let nearby_resp = client
.get_cabs(grpc::RequestOptions::new(), nearby_req)
.join_metadata_result();
let nearby_resp = executor::block_on(nearby_resp);
match nearby_resp {
Err(e) => panic!("{:?}", e),
Ok((_, cabs, _)) => println!("{:?}", cabs),
}
}

编译

cargo build//编译

编译完成后的目录结构为:

use_grpc
|----- build.rs
|----- Cargo.toml
|----- foobar.proto
|----- src
|----- lib.rs
|----- foobar_grpc.rs
|----- foobar.rs
|----- bin
|----- client.rs
|----- server.rs

其中foobar_grpc.rs和foobar.rs为编译生成的文件。

运行

进入到target/Debug目录下。

  • 先运行服务端

./server

  • 运行客户端

./client


举报

相关推荐

0 条评论