- 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

@@ -0,0 +1,59 @@
use reqwest::Client;
use serde::Serialize;
#[derive(Serialize)]
struct ConsulRegistration {
name: String,
address: String,
port: u16,
check: ConsulCheck,
}
#[derive(Serialize)]
struct ConsulCheck {
http: String,
interval: String,
}
pub async fn register_service(
consul_url: &str,
service_name: &str,
service_address: &str,
service_port: u16,
health_check_url: &str,
) -> Result<(), Box<dyn std::error::Error>> {
let registration = ConsulRegistration {
name: service_name.to_string(),
address: service_address.to_string(),
port: service_port,
check: ConsulCheck {
http: health_check_url.to_string(),
interval: "10s".to_string(), // Health check interval
},
};
let client = Client::new();
let consul_register_url = format!("{}/v1/agent/service/register", consul_url);
client
.put(&consul_register_url)
.json(&registration)
.send()
.await?
.error_for_status()?; // Ensure response is successful
Ok(())
}
pub async fn deregister_service(consul_url: &str, service_name: &str) -> Result<(), Box<dyn std::error::Error>> {
let client = Client::new();
let consul_deregister_url = format!("{}/v1/agent/service/deregister/{}", consul_url, service_name);
client
.put(&consul_deregister_url)
.send()
.await?
.error_for_status()?; // Ensure response is successful
Ok(())
}