Skip to content

Commit f35dd48

Browse files
authored
Build a gRPC server with Tonic
1 parent 645fc2a commit f35dd48

File tree

1 file changed

+56
-5
lines changed

1 file changed

+56
-5
lines changed

protobuf-grpc.md

Lines changed: 56 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -21,12 +21,63 @@ TBD
2121
2222
## Tonic
2323
Tonic is a crate implementing the gRPC protocol on top of HTTP/2 and Prost.
24-
```shell
25-
cargo add tonic
24+
25+
### Build a gRPC server with Tonic
26+
27+
File hierarchy used for this section.
28+
29+
```
30+
proto/
31+
metrics/
32+
v1/
33+
metrics_service.proto
34+
...
35+
src/
36+
lib.rs
37+
Cargo.toml
38+
build.rs
2639
```
2740
28-
### Build gRPC spec with Tonic
29-
TBD
41+
Add the following dependencies in Cargo.toml.
42+
43+
```toml
44+
[dependencies]
45+
tonic = "0.5"
46+
prost = "0.8"
47+
48+
[build-dependencies]
49+
tonic-build = "0.5"
50+
```
51+
52+
Add the following `build.rs` file at the root level.
53+
54+
```rust
55+
fn main() -> Result<(), Box<dyn std::error::Error>> {
56+
tonic_build::configure().compile(
57+
&[
58+
"proto/metrics/v1/metrics_service.proto",
59+
...
60+
],
61+
&["proto"],
62+
)?;
63+
64+
Ok(())
65+
}
66+
```
67+
68+
Declare the modules generated by Tonic in lib.rs
69+
70+
```rust
71+
pub mod metrics {
72+
pub mod proto {
73+
pub mod v1 {
74+
tonic::include_proto!("metrics.v1");
75+
}
76+
}
77+
78+
...
79+
}
80+
```
3081
3182
### Multiple instances of a gRPC service listening to the same port
3283
@@ -58,4 +109,4 @@ Server::builder()
58109
.serve_with_incoming(incoming)
59110
.await
60111
.unwrap();
61-
```
112+
```

0 commit comments

Comments
 (0)