flare_rpc_core/discover/
registry.rs

1use async_trait::async_trait;
2use serde::{Deserialize, Serialize};
3use std::collections::HashMap;
4use log;
5
6/// 服务注册接口
7#[async_trait]
8pub trait Registry: Send + Sync + Clone + 'static {
9    type Error: std::error::Error + Send + Sync;
10
11    /// 注册服务
12    async fn register(&self, registration: Registration) -> Result<(), Self::Error>;
13
14    /// 注销服务
15    async fn deregister(&self, service_id: &str) -> Result<(), Self::Error>;
16
17    /// 服务心跳
18    async fn heartbeat(&self, service_id: &str) -> Result<(), Self::Error>;
19}
20
21/// 服务注册信息
22#[derive(Default, Clone, Serialize, Deserialize)]
23pub struct Registration {
24    pub name: String,
25    pub id: String,
26    pub tags: Vec<String>,
27    pub address: String,
28    pub port: u16,
29    pub weight: u32,
30    pub meta: HashMap<String, String>,
31    pub version: String,
32}
33
34impl Registration {
35    pub fn new(
36        name: String,
37        id: String,
38        tags: Vec<String>,
39        address: String,
40        port: u16,
41        weight: u32,
42        meta: HashMap<String, String>,
43        version: String,
44    ) -> Self {
45        Self {
46            name,
47            id,
48            tags,
49            address,
50            port,
51            weight,
52            meta,
53            version,
54        }
55    }
56}
57
58/// 默认的日志注册器实现
59#[derive(Debug, Clone)]
60pub struct LogRegistry;
61
62impl LogRegistry {
63    pub fn new() -> Self {
64        Self
65    }
66}
67
68#[async_trait]
69impl Registry for LogRegistry {
70    type Error = std::io::Error;
71
72    async fn register(&self, registration: Registration) -> Result<(), Self::Error> {
73        log::info!("Registering service: {} (id: {})", registration.name, registration.id);
74        Ok(())
75    }
76
77    async fn deregister(&self, service_id: &str) -> Result<(), Self::Error> {
78        log::info!("Deregistering service: {}", service_id);
79        Ok(())
80    }
81
82    async fn heartbeat(&self, service_id: &str) -> Result<(), Self::Error> {
83        log::debug!("Service heartbeat: {}", service_id);
84        Ok(())
85    }
86}