- add: gRPC health check for gRPC services

This commit is contained in:
2025-03-10 03:56:47 -04:00
parent d583ca1228
commit ae04d2bf5b
12 changed files with 70 additions and 69 deletions

View File

@@ -26,7 +26,6 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
let addr = env::var("LISTEN_ADDR").unwrap_or_else(|_| "0.0.0.0".to_string());
let port = env::var("DATABASE_SERVICE_PORT").unwrap_or_else(|_| "50052".to_string());
let health_port = env::var("HEALTH_CHECK_PORT").unwrap_or_else(|_| "8080".to_string());
let database_url = std::env::var("DATABASE_URL").expect("DATABASE_URL must be set");
let redis_url =
@@ -37,12 +36,11 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
let service_address =
env::var("DATABASE_SERVICE_ADDR").unwrap_or_else(|_| "127.0.0.1".to_string());
let service_port = port.clone();
let health_check_url = format!("http://{}:{}/health", service_address, health_port);
// Register service with Consul
let service_id = consul_registration::get_or_generate_service_id(env!("CARGO_PKG_NAME"));
let version = env!("CARGO_PKG_VERSION").to_string();
let tags = vec![version];
let tags = vec![version, "grpc".to_string()];
let meta = HashMap::new();
consul_registration::register_service(
&consul_url,
@@ -52,9 +50,10 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
service_port.parse().unwrap_or(50052),
tags,
meta,
&health_check_url,
None,
None,
)
.await?;
.await?;
consul_registration::start_health_check(addr.as_str()).await?;
@@ -70,10 +69,14 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
let db = Arc::new(Database::new(pool, redis_cache));
let my_service = MyDatabaseService { db };
let (mut health_reporter, health_service) = tonic_health::server::health_reporter();
health_reporter.set_serving::<UserServiceServer<MyDatabaseService>>().await;
// Pass `shared_cache` into services as needed
info!("Database Service running on {}", address);
tokio::spawn(
Server::builder()
.add_service(health_service)
.add_service(UserServiceServer::new(my_service.clone()))
.add_service(CharacterDbServiceServer::new(my_service))
.serve(address),