- update: major refactor of the database-service to make it easy to add newer api services

- add: character database api
This commit is contained in:
2024-12-17 01:58:18 -05:00
parent 267422adb4
commit 52455d6ffc
18 changed files with 378 additions and 180 deletions

View File

@@ -1,19 +1,18 @@
use std::collections::HashMap;
use database::database_service_server::DatabaseServiceServer;
use database_service::database;
use database_service::db::Database;
use database_service::grpc::MyDatabaseService;
use database_service::grpc::database_service::MyDatabaseService;
use database_service::grpc::user_service_server::UserServiceServer;
use database_service::grpc::character_service_server::CharacterServiceServer;
use database_service::redis_cache::RedisCache;
use dotenv::dotenv;
use sqlx::postgres::PgPoolOptions;
use std::env;
use std::net::ToSocketAddrs;
use std::str::FromStr;
use std::sync::Arc;
use tokio::{select, signal};
use tokio::sync::Mutex;
use tonic::transport::Server;
use tracing::{info, Level};
use warp::Filter;
use utils::consul_registration;
#[tokio::main]
@@ -32,15 +31,14 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
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 = env::var("DATABASE_SERVICE_ADDR").unwrap_or_else(|_| "127.0.0.1".to_string());;
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);
let health_check_endpoint_addr = format!("{}:{}", service_address, health_port);
// Register service with Consul
let service_id = consul_registration::generate_service_id();
let tags = vec!["version-1.0".to_string()];
let mut meta = HashMap::new();
let meta = HashMap::new();
consul_registration::register_service(
&consul_url,
service_id.as_str(),
@@ -63,18 +61,17 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
.await
.expect("Failed to create PostgreSQL connection pool");
let redis_cache = RedisCache::new(&redis_url);
let cache = Arc::new(redis_cache); // Share the cache instance between tasks
let database_service = MyDatabaseService {
db: Database::new(pool, cache).await,
};
let redis_cache = Arc::new(Mutex::new(RedisCache::new(&redis_url)));
let db = Arc::new(Database::new(pool, redis_cache));
let my_service = MyDatabaseService { db };
// Pass `shared_cache` into services as needed
info!("Database Service running on {}", address);
tokio::spawn(Server::builder()
.add_service(DatabaseServiceServer::new(database_service))
.serve(address));
.add_service(UserServiceServer::new(my_service.clone()))
.add_service(CharacterServiceServer::new(my_service))
.serve(address));
select! {
_ = signal::ctrl_c() => {},