tonic is a Rust-based asynchronous gRPC framework for building high-performance, type-safe gRPC clients and servers. It is built on tokio and hyper, has good performance and ecological integration, and is widely used in microservice communication, remote calls and other scenarios.
Dependencies
= { = "<version>" }
= { = "0.13" }
= { = "0.13" }
Configuration items
[]
= "172.20.10.4" # IP address of the network interface to be bound, default 0.0.0.0
= 8000 # Port number to be bound, default 9090
= true # Whether to enable graceful shutdown, default false
Service implementation
Interface definition based on protobuf protocol
syntax = "proto3";
package helloworld;
// 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;
}
Add protobuf compilation dependency in Cargo.toml
[]
= "0.13"
Add build.rs in the same directory as Cargo.toml to compile the interface definition of protobuf and generate the corresponding rust code
Implement the corresponding interface
use Service;
use App;
use GrpcPlugin;
use ;
use ;
use ;
/// Import the interface defined by protobuf into the project
async
/// Derive Service and specify Grpc Server. The Grpc plug-in will automatically register the service on tonic
;
/// Implement the interface defined by protobuf
Complete code reference grpc-example