How to run a grpc and grpc-web server on different ports? #740
-
I'm wondering how to run multiple tonic servers concurrently. I currently have this working: use apis::user::v1::user_service_server::UserServiceServer;
use tonic::transport::Server;
mod srv {
use apis::user::v1::{user_service_server::UserService, GetUserRequest, User};
use tonic::{Request, Response};
pub struct Srv {}
#[tonic::async_trait]
impl UserService for Srv {
async fn get_user(
&self,
_request: Request<GetUserRequest>,
) -> Result<Response<User>, tonic::Status> {
let mut u = User::default();
u.name = "test".to_owned();
Ok(Response::new(u))
}
}
}
async fn wait() {
println!("server listening");
tokio::signal::ctrl_c().await.ok();
println!("shutdown complete");
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let grpc_server = Server::builder()
.add_service(UserServiceServer::new(srv::Srv {}))
.serve_with_shutdown("0.0.0.0:50051".parse()?, wait());
let grpc_web_server = Server::builder()
.accept_http1(true)
.add_service(tonic_web::enable(UserServiceServer::new(srv::Srv {})))
.serve_with_shutdown("0.0.0.0:50052".parse()?, wait());
let grpc_handle = tokio::spawn(grpc_server);
let grpc_web_handle = tokio::spawn(grpc_web_server);
let _ = tokio::try_join!(grpc_handle, grpc_web_handle)?;
Ok(())
} but I need to pass a db pool into the |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 5 replies
-
Wait I'm confused. You example already runs two servers on different ports... To answer what appears to be your real question:
pub struct Srv { db_pool: DatabasePool }
// and then create it with
.add_service(UserServiceServer::new(srv::Srv { db_pool }))
// and use it like any other struct field
async fn get_user(
&self,
_request: Request<GetUserRequest>,
) -> Result<Response<User>, tonic::Status> {
// access the pool
self.db_pool.do_something();
// ...
} |
Beta Was this translation helpful? Give feedback.
-
From what I understand, I suppose that it’s not possible to have only one gRPC server that will handle both gRPC web (HTTP1) and normal gRPC (HTTP2) at the same time? |
Beta Was this translation helpful? Give feedback.
Wait I'm confused. You example already runs two servers on different ports...
To answer what appears to be your real question:
Srv
is an ordinary struct so you can do