Skip to content

Instantly share code, notes, and snippets.

@yzhong52
Last active May 9, 2022 02:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yzhong52/076b91e05d243f23ac711904149a29f3 to your computer and use it in GitHub Desktop.
Save yzhong52/076b91e05d243f23ac711904149a29f3 to your computer and use it in GitHub Desktop.
rust_grpc_demo
syntax = "proto3";
package bookstore;
// The book store service definition.
service Bookstore {
// Retrieve a book
rpc GetBook(GetBookRequest) returns (GetBookResponse) {}
}
// The request with a id of the book
message GetBookRequest {
string id = 1;
}
// The response details of a book
message GetBookResponse {
string id = 1;
string name = 2;
string author = 3;
int32 year = 4;
}
use std::{env, path::PathBuf};
fn main() {
let proto_file = "./proto/bookstore.proto";
tonic_build::configure()
.build_server(true)
.out_dir("./src")
.compile(&[proto_file], &["."])
.unwrap_or_else(|e| panic!("protobuf compile error: {}", e));
println!("cargo:rerun-if-changed={}", proto_file);
}
use std::{env, path::PathBuf};
fn main() {
let proto_file = "./proto/book_store.proto";
let out_dir = PathBuf::from(env::var("OUT_DIR").unwrap()); // Add this
tonic_build::configure()
.build_server(true)
.file_descriptor_set_path(out_dir.join("greeter_descriptor.bin")) // Add this
.out_dir("./src")
.compile(&[proto_file], &["."])
.unwrap_or_else(|e| panic!("protobuf compile error: {}", e));
println!("cargo:rerun-if-changed={}", proto_file);
}
[package]
name = "rust_grpc_demo"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
tonic = "0.7.1"
tokio = { version = "1.18.0", features = ["macros", "rt-multi-thread"] }
prost = "0.10.1"
[build-dependencies]
tonic-build = "0.7.2"
use tonic::{transport::Server, Request, Response, Status};
use bookstore::bookstore_server::{Bookstore, BookstoreServer};
use bookstore::{GetBookRequest, GetBookResponse};
mod bookstore {
include!("bookstore.rs");
}
#[derive(Default)]
pub struct BookStoreImpl {}
#[tonic::async_trait]
impl Bookstore for BookStoreImpl {
async fn get_book(
&self,
request: Request<GetBookRequest>,
) -> Result<Response<GetBookResponse>, Status> {
println!("Request from {:?}", request.remote_addr());
let response = GetBookResponse {
id: request.into_inner().id,
author: "Peter".to_owned(),
name: "Zero to One".to_owned(),
year: 2014,
};
Ok(Response::new(response))
}
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let addr = "[::1]:50051".parse().unwrap();
let bookstore = BookStoreImpl::default();
println!("Bookstore server listening on {}", addr);
Server::builder()
.add_service(BookstoreServer::new(bookstore))
.serve(addr)
.await?;
Ok(())
}
use tonic::{transport::Server, Request, Response, Status};
use bookstore::bookstore_server::{Bookstore, BookstoreServer};
use bookstore::{GetBookRequest, GetBookResponse};
mod bookstore {
include!("bookstore.rs");
// Add this
pub(crate) const FILE_DESCRIPTOR_SET: &[u8] =
tonic::include_file_descriptor_set!("greeter_descriptor");
}
#[derive(Default)]
pub struct BookStoreImpl {}
#[tonic::async_trait]
impl Bookstore for BookStoreImpl {
async fn get_book(
&self,
request: Request<GetBookRequest>,
) -> Result<Response<GetBookResponse>, Status> {
println!("Request from {:?}", request.remote_addr());
let response = GetBookResponse {
id: request.into_inner().id,
author: "Peter".to_owned(),
name: "Zero to One".to_owned(),
year: 2014,
};
Ok(Response::new(response))
}
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let addr = "[::1]:50051".parse().unwrap();
let bookstore = BookStoreImpl::default();
// Add this
let reflection_service = tonic_reflection::server::Builder::configure()
.register_encoded_file_descriptor_set(bookstore::FILE_DESCRIPTOR_SET)
.build()
.unwrap();
println!("Bookstore server listening on {}", addr);
Server::builder()
.add_service(BookstoreServer::new(bookstore))
.add_service(reflection_service) // Add this
.serve(addr)
.await?;
Ok(())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment