You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@dubbo.apache.org by ya...@apache.org on 2022/11/15 12:55:33 UTC
[dubbo-rust] branch main updated: Rft: default config init and Dubbo::init (#66)
This is an automated email from the ASF dual-hosted git repository.
yangyang pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/dubbo-rust.git
The following commit(s) were added to refs/heads/main by this push:
new cfa1214 Rft: default config init and Dubbo::init (#66)
cfa1214 is described below
commit cfa1214ac7667de8ab00178f415caae06d239acd
Author: xuankun zheng <32...@users.noreply.github.com>
AuthorDate: Tue Nov 15 20:55:28 2022 +0800
Rft: default config init and Dubbo::init (#66)
* Rft: default config init and Dubbo::init
* Fix: make the GLOBAL_ROOT_CONFIG initialize lazily
Co-authored-by: zkx <zh...@163.com>
---
config/Cargo.toml | 1 +
config/src/config.rs | 33 +++++++--------
config/src/protocol.rs | 2 +-
dubbo/src/framework.rs | 111 ++++++++++++++++++++++++-------------------------
4 files changed, 72 insertions(+), 75 deletions(-)
diff --git a/config/Cargo.toml b/config/Cargo.toml
index 27833cc..f50da91 100644
--- a/config/Cargo.toml
+++ b/config/Cargo.toml
@@ -14,3 +14,4 @@ serde = {version="1.0.138", features = ["derive"]}
serde_yaml = "0.9.4"
tracing = "0.1"
lazy_static = "1.3.0"
+once_cell = "1.16.0"
diff --git a/config/src/config.rs b/config/src/config.rs
index 4e7edea..36aa047 100644
--- a/config/src/config.rs
+++ b/config/src/config.rs
@@ -15,9 +15,9 @@
* limitations under the License.
*/
-use std::{collections::HashMap, env, fs, sync::RwLock};
+use std::{collections::HashMap, env, fs};
-use lazy_static::lazy_static;
+use once_cell::sync::OnceCell;
use serde::{Deserialize, Serialize};
use super::protocol::ProtocolConfig;
@@ -26,9 +26,7 @@ use super::service::ServiceConfig;
pub const DUBBO_CONFIG_PATH: &str = "./dubbo.yaml";
-lazy_static! {
- pub static ref GLOBAL_ROOT_CONFIG: RwLock<Option<RootConfig>> = RwLock::new(None);
-}
+pub static GLOBAL_ROOT_CONFIG: OnceCell<RootConfig> = OnceCell::new();
/// used to storage all structed config, from some source: cmd, file..;
/// Impl Config trait, business init by read Config trait
@@ -51,19 +49,13 @@ pub struct RootConfig {
pub data: HashMap<String, String>,
}
-pub fn get_global_config() -> RootConfig {
- if GLOBAL_ROOT_CONFIG.read().unwrap().as_ref().is_none() {
- {
- tracing::debug!("current path: {:?}", env::current_dir());
- let c = match RootConfig::new().load() {
- Ok(v) => v,
- Err(err) => panic!("Failed to load global config, error: {}", err),
- };
- *GLOBAL_ROOT_CONFIG.write().unwrap() = Some(c);
- }
- }
-
- return GLOBAL_ROOT_CONFIG.read().unwrap().as_ref().unwrap().clone();
+pub fn get_global_config() -> &'static RootConfig {
+ GLOBAL_ROOT_CONFIG.get_or_init(|| {
+ tracing::debug!("current path: {:?}", env::current_dir());
+ RootConfig::new()
+ .load()
+ .unwrap_or_else(|err| panic!("Failed to load global config, error: {}", err))
+ })
}
impl RootConfig {
@@ -151,6 +143,11 @@ impl RootConfig {
);
// self.data.insert("dubbo.consume.", v)
}
+
+ #[inline]
+ pub fn leak(self) -> &'static Self {
+ Box::leak(Box::new(self))
+ }
}
impl Config for RootConfig {
diff --git a/config/src/protocol.rs b/config/src/protocol.rs
index 654f0d8..2453152 100644
--- a/config/src/protocol.rs
+++ b/config/src/protocol.rs
@@ -46,7 +46,7 @@ impl ProtocolConfig {
Self { params, ..self }
}
- pub fn to_url(self) -> String {
+ pub fn to_url(&self) -> String {
format!("{}://{}:{}", self.name, self.ip, self.port)
}
}
diff --git a/dubbo/src/framework.rs b/dubbo/src/framework.rs
index 06c2754..4c08604 100644
--- a/dubbo/src/framework.rs
+++ b/dubbo/src/framework.rs
@@ -33,7 +33,7 @@ pub struct Dubbo {
protocols: HashMap<String, Vec<Url>>,
registries: HashMap<String, Url>,
service_registry: HashMap<String, Vec<Url>>, // registry: Urls
- config: Option<RootConfig>,
+ config: Option<&'static RootConfig>,
}
impl Dubbo {
@@ -47,71 +47,60 @@ impl Dubbo {
}
}
- pub fn with_config(mut self, c: RootConfig) -> Self {
- self.config = Some(c);
+ pub fn with_config(mut self, config: RootConfig) -> Self {
+ self.config = Some(config.leak());
self
}
pub fn init(&mut self) {
- if self.config.is_none() {
- self.config = Some(get_global_config())
- }
-
- let conf = self.config.as_ref().unwrap();
+ let conf = self.config.get_or_insert_with(|| get_global_config());
tracing::debug!("global conf: {:?}", conf);
for (name, url) in conf.registries.iter() {
- self.registries
- .insert(name.to_string(), Url::from_url(url).unwrap());
+ self.registries.insert(
+ name.clone(),
+ Url::from_url(url).expect(&format!("url: {url} parse failed.")),
+ );
}
- for (service_name, c) in conf.provider.services.iter() {
- let u = if c.protocol_configs.is_empty() {
- let protocol = match conf.protocols.get(&c.protocol) {
- Some(v) => v.to_owned(),
- None => {
- tracing::warn!("protocol {:?} not exists", c.protocol);
- continue;
- }
- };
- let protocol_url =
- format!("{}/{}/{}", protocol.to_url(), c.name.clone(), service_name);
- Url::from_url(&protocol_url)
- } else {
- let protocol = match c.protocol_configs.get(&c.protocol) {
- Some(v) => v.to_owned(),
- None => {
- tracing::warn!("protocol {:?} not exists", c.protocol);
- continue;
- }
- };
- let protocol_url =
- format!("{}/{}/{}", protocol.to_url(), c.name.clone(), service_name);
- Url::from_url(&protocol_url)
+ for (service_name, service_config) in conf.provider.services.iter() {
+ let protocol_url = match service_config
+ .protocol_configs
+ .get(&service_config.protocol)
+ {
+ Some(protocol_url) => protocol_url,
+ None => {
+ let Some(protocol_url) = conf.protocols.get(&service_config.protocol) else {
+ tracing::warn!("protocol: {:?} not exists", service_config.protocol);
+ continue;
+ };
+ protocol_url
+ }
};
- tracing::info!("url: {:?}", u);
- if u.is_none() {
- continue;
- }
-
- let u = u.unwrap();
-
- let reg_url = self.registries.get(&c.registry).unwrap();
- if self.service_registry.get(&c.name).is_some() {
- self.service_registry
- .get_mut(&c.name)
- .unwrap()
- .push(reg_url.clone());
- } else {
- self.service_registry
- .insert(c.name.clone(), vec![reg_url.clone()]);
- }
-
- if self.protocols.get(&c.protocol).is_some() {
- self.protocols.get_mut(&c.protocol).unwrap().push(u);
- } else {
- self.protocols.insert(c.protocol.clone(), vec![u]);
- }
+ let protocol_url = format!(
+ "{}/{}/{}",
+ &protocol_url.to_url(),
+ service_config.name,
+ service_name
+ );
+ tracing::info!("url: {}", protocol_url);
+
+ let protocol_url = Url::from_url(&protocol_url)
+ .expect(&format!("protocol url: {protocol_url} parse failed."));
+ self.protocols
+ .entry(service_config.name.clone())
+ .and_modify(|urls| urls.push(protocol_url.clone()))
+ .or_insert(vec![protocol_url]);
+
+ let registry = &service_config.registry;
+ let reg_url = self
+ .registries
+ .get(registry)
+ .expect(&format!("can't find the registry: {registry}"));
+ self.service_registry
+ .entry(service_config.name.clone())
+ .and_modify(|urls| urls.push(reg_url.to_owned()))
+ .or_insert(vec![reg_url.to_owned()]);
}
}
@@ -134,3 +123,13 @@ impl Dubbo {
let _res = future::join_all(async_vec).await;
}
}
+
+impl Drop for Dubbo {
+ fn drop(&mut self) {
+ unsafe {
+ if let Some(config) = self.config.take() {
+ let _ = Box::from_raw(config as *const RootConfig as *mut RootConfig);
+ }
+ }
+ }
+}