- add: service discovery protocol using consul

This commit is contained in:
2024-11-26 01:59:01 -05:00
parent 113ab5a4ac
commit ab7728837c
7 changed files with 266 additions and 16 deletions

View File

@@ -1,5 +1,7 @@
use warp::Filter;
use dotenv::dotenv;
use std::env;
use std::net::ToSocketAddrs;
use tonic::transport::Server;
use database_service::db::Database;
use database_service::redis_cache::RedisCache;
@@ -8,7 +10,9 @@ use std::sync::Arc;
use database_service::database;
use database_service::grpc::MyDatabaseService;
use sqlx::postgres::PgPoolOptions;
use tokio::task;
mod consul_registration;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
@@ -19,11 +23,42 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
.with_timer(tracing_subscriber::fmt::time::ChronoLocal::rfc_3339())
.init();
let addr = env::var("DATABASE_SERVICE_ADDR").unwrap_or_else(|_| "127.0.0.1:50052".to_string());
let addr = env::var("DATABASE_SERVICE_ADDR").unwrap_or_else(|_| "127.0.0.1".to_string());
let port = env::var("DATABASE_SERVICE_PORT").unwrap_or_else(|_| "50052".to_string());
let database_url = std::env::var("DATABASE_URL").expect("DATABASE_URL must be set");
let redis_url = std::env::var("REDIS_URL").unwrap_or_else(|_| "redis://127.0.0.1:6379".to_string());
let addr = addr.parse().expect("Invalid address");
let consul_url = env::var("CONSUL_URL").unwrap_or_else(|_| "http://127.0.0.1:8500".to_string());
let service_name = env::var("SERVICE_NAME").unwrap_or_else(|_| "database-service".to_string());
let service_address = addr.as_str();
let service_port = port.clone();
let health_check_url = format!("http://{}:{}/health", service_address, service_port);
let health_check_endpoint_addr = format!("{}:8080", service_address);
// Register service with Consul
consul_registration::register_service(
&consul_url,
service_name.as_str(),
service_address,
service_port.parse().unwrap_or(50052),
&health_check_url,
)
.await?;
// Start health-check endpoint
let health_route = warp::path!("health")
.map(|| warp::reply::with_status("OK", warp::http::StatusCode::OK));
tokio::spawn(warp::serve(health_route).run(health_check_endpoint_addr.to_socket_addrs()?.next().unwrap()));
tokio::spawn(async move {
tokio::signal::ctrl_c().await.unwrap();
consul_registration::deregister_service(&consul_url, service_name.as_str()).await.expect("");
});
let full_addr = format!("{}:{}", &addr, port);
let address = full_addr.parse().expect("Invalid address");
let pool = PgPoolOptions::new()
.max_connections(5)
.connect(&database_url)
@@ -38,10 +73,10 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
};
// Pass `shared_cache` into services as needed
println!("Database Service running on {}", addr);
println!("Database Service running on {}", address);
Server::builder()
.add_service(DatabaseServiceServer::new(database_service))
.serve(addr)
.serve(address)
.await?;
Ok(())