Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add auto read yml config and update boot test #45

Merged
merged 5 commits into from
Jun 22, 2022
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion summer-boot-autoconfigure/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,13 @@ description = "summer boot autoconfigure"
authors = [
"James Zow <[email protected]>"
]
license = "Apache-2.0"
license = "Apache-2.0"

[dependencies]
serde = { version = "1", features = ["derive"] }
serde_yaml = "0.8"
serde_json = "1.0.75"
schemars = "0.8.8"

#file
toml = "0.5"
3 changes: 3 additions & 0 deletions summer-boot-autoconfigure/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
mod read_yml;

pub use read_yml::*;
151 changes: 151 additions & 0 deletions summer-boot-autoconfigure/src/read_yml.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
use serde::{Deserialize, Serialize};
use schemars::schema::RootSchema;
use serde_yaml::from_str as yaml_from_str;
use serde_json::{from_str as json_from_str, to_string_pretty};
use std::{fs::{read_to_string, self}, io::Read};

#[derive(Serialize, Deserialize,Debug)]
pub struct GlobalConfig {
pub mysql: Mysql,
pub server: Server,
}

#[derive(Debug,Serialize, Deserialize)]
pub struct Mysql {
pub host: String,
pub port: u32,
pub user: String,
pub password: String,
pub db: String,
pub pool_min_idle: u64,
pub pool_max_open: u64,
pub timeout_seconds: u64,
}

#[derive(Debug,Serialize, Deserialize)]
pub struct Server {
pub port: u32,
pub context_path: String,
}

#[derive(Serialize, Deserialize)]
pub struct Profiles {
pub active: String,
}

#[derive(Serialize, Deserialize)]
pub struct EnvConfig {
pub profiles: Profiles,
}

#[derive(Debug, Deserialize)]
struct ConfWorkSpace {
workspace: Option<Member>,
package: Option<Name>,
}

/// 匹配workspace下的member数组格式
#[derive(Debug, Deserialize)]
struct Member {
members: Option<Vec<String>>,
}

/// 匹配package下的name字段
#[derive(Debug, Deserialize)]
struct Name {
name: String,
}

///
/// 获取toml package_name
///
fn get_package_name() -> String {
let mut cargo_toml = fs::File::open("Cargo.toml").unwrap();
let mut content = String::new();
cargo_toml.read_to_string(&mut content).unwrap();

let mut projects = Vec::<String>::new();

if let Ok(conf_work_space) = toml::from_str::<ConfWorkSpace>(&content) {
if let Some(workspace) = conf_work_space.workspace {
if let Some(members) = workspace.members {
for member in members {
projects.push(format!("{}/src/resources", member));
for project in &projects {
let check = fs::File::open(project).is_ok();
if check == true {
return member;
}
}
}
}
} else if projects.len() == 0 {
if let Some(package) = conf_work_space.package {
return package.name;
}
}
}

String::from("_")
}

///
/// 加载环境配置
///
pub fn load_env_conf() -> Option<EnvConfig> {
let package_name = get_package_name();

let path = format!("{}/src/resources/application.yml", package_name);

println!("{}", path);

let schema = yaml_from_str::<RootSchema>(
&read_to_string(&path).unwrap_or_else(|_| panic!("Error loading configuration file {}, please check the configuration!", &path)),
);
return match schema {
Ok(json) => {
let data = to_string_pretty(&json).expect("resources/application.yml file data error!");
let p: EnvConfig = json_from_str(&*data).expect("Failed to transfer JSON data to EnvConfig object!");
return Some(p);
}
Err(err) => {
println!("{}", err);
None
}
};
}

///
/// 根据环境配置加载全局配置
///
/// action dev 开始环境 test 测试环境 prod 生产环境
///
pub fn load_global_config(action: String) -> Option<GlobalConfig> {
let package_name = get_package_name();

let path = format!("{}/src/resources/application-{}.yml", package_name, &action);
let schema = yaml_from_str::<RootSchema>(
&read_to_string(&path).unwrap_or_else(|_| panic!("Error loading configuration file {}, please check the configuration!", &path)),
);
return match schema {
Ok(json) => {
let data = to_string_pretty(&json).unwrap_or_else(|_| panic!("{} file data error!, please check the configuration!", path));
let p = json_from_str(&*data).expect("Failed to transfer JSON data to BriefProConfig object!");
return Some(p);
}
Err(err) => {
println!("{}", err);
None
}
};
}

///
/// 先加载环境配置 在根据当前加载的环境 去加载相应的信息
///
pub fn load_conf() -> Option<GlobalConfig> {
if let Some(init) = load_env_conf() {
return load_global_config(init.profiles.active);
}
None
}
5 changes: 4 additions & 1 deletion summer-boot-tests/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@ serde_yaml = "0.8"
serde_json = "1.0.75"
lazy_static = "1.4.0"
schemars = "0.8.8"
tokio = { version = "1.19.2", features = ["full"] }

#summer
summer-boot-macro = {version = "0.1.0", path = "../summer-boot-macro"}
summer-boot = {version = "0.1.0", path = "../summer-boot"}
tokio = { version = "1", features = ["full"]}
summer-boot-autoconfigure = { version = "0.1.0", path = "../summer-boot-autoconfigure"}
2 changes: 1 addition & 1 deletion summer-boot-tests/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ use schemars::schema::RootSchema;
use serde_yaml::from_str as yaml_from_str;
use serde_json::{from_str as json_from_str, to_string_pretty};
use std::fs::read_to_string;
use tokio::net::TcpListener;
#[derive(Serialize, Deserialize,Debug)]
pub struct GlobalConfig {
pub mysql: Mysql,
Expand Down Expand Up @@ -84,6 +83,7 @@ pub fn load_conf() -> Option<GlobalConfig> {
}
None
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down
9 changes: 3 additions & 6 deletions summer-boot-tests/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,23 +1,20 @@
use serde::Deserialize;
use summer_boot::{Request, Result};
use summer_boot::log;
use serde_json::Value;

#[derive(Debug, Deserialize)]
struct User {
name: String,
age: u16,
}

#[summer_boot::auto_scan]
#[summer_boot::main]
async fn main() {
log::start();
let mut app = summer_boot::new();
app.listen("127.0.0.1:8080").await.unwrap();
summer_boot::run().await.unwrap();
}

#[summer_boot::post("/test/api")]
async fn test_api(mut req: Request<()>) -> Result {
let User { name, age } = req.body_json().await?;
Ok(format!("Hello, {}! {} years old", name, age).into())
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,7 @@ mysql:
pool_max_open: 32
#连接超时时间单位秒
timeout_seconds: 15

server:
port: 7798
context_path: /
1 change: 1 addition & 0 deletions summer-boot/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ futures-util = "0.3.6"

# summer dependencies
summer-boot-actuator = { version = "0.1.0", path = "../summer-boot-actuator"}
summer-boot-autoconfigure = { version = "0.1.0", path = "../summer-boot-autoconfigure"}
summer-boot-macro = { version = "0.1.0", path = "../summer-boot-macro", optional = true }

#log
Expand Down
11 changes: 10 additions & 1 deletion summer-boot/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@ pub mod web2;
pub mod common;
pub mod log;

use async_std::io;
use serde_json::ser::State;
use web2::tcp::ToListener;
use web2::{
utils,
aop,
Expand Down Expand Up @@ -29,9 +32,15 @@ pub fn new() -> Server<()> {
Server::new()
}

/// 自动扫描 日志开启 读取yml
pub async fn run() -> io::Result<()>
{
Server::run().await
}

pub fn with_state<State>(state: State) -> Server<State>
where
State: Clone + Send + Sync + 'static,
State: Clone + Copy + Send + Sync + 'static,
{
Server::with_state(state)
}
Expand Down
38 changes: 33 additions & 5 deletions summer-boot/src/web2/server/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,14 @@ use crate::{Endpoint, Request, Route};

use async_std::io;
use async_std::sync::Arc;
use serde_json::Value;

use tcp::{Listener, ToListener};
use utils::middleware::{Middleware, Next};
use utils::util;
use gateway::router::{Router, Selection};

use summer_boot_autoconfigure;

/// HTTP服务器。
///
/// 服务器由 *state*, *endpoints* 和 *middleware* 组成。
Expand Down Expand Up @@ -58,6 +60,35 @@ impl Server<()> {
pub fn new() -> Self {
Self::with_state(())
}


/// 创建一个summer boot web2 server.
///
/// 默认开启日志记录
/// 读取yml然后绑定监听
///
pub async fn run() -> io::Result<()> {
log::start();
let server = Self::with_state(());

let mut listener_addr = String::from("0.0.0.0:");

let config = summer_boot_autoconfigure::load_conf();

if let Some(config) = config {
let read_server = serde_json::to_string(&config.server).unwrap();

let v: Value = serde_json::from_str(&read_server).unwrap();
let port = v["port"].to_string();
listener_addr.push_str(&port);
}

server.listen(listener_addr).await.unwrap();

Ok(())
}


}

impl Default for Server<()> {
Expand Down Expand Up @@ -107,10 +138,7 @@ where
router: Arc::new(Router::new()),
middleware: Arc::new(vec![
// 暂时没有使用到cookies
#[cfg(feature = "cookies")]
Arc::new(cookies::CookiesMiddleware::new()),
#[cfg(feature = "logger")]
Arc::new(log::LogMiddleware::new()),
Arc::new(log::LoggingSystem::new()),
]),
state,
}
Expand Down