NAC_Blockchain/nac_wallet_service/src/config.rs

70 lines
2.7 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

use deadpool_postgres::{Config as PgConfig, Pool, Runtime};
use tokio_postgres::NoTls;
use std::env;
/// 应用配置
#[derive(Clone, Debug)]
pub struct AppConfig {
pub host: String,
pub port: u16,
pub jwt_secret: String,
pub admin_jwt_secret: String,
pub db_host: String,
pub db_port: u16,
pub db_name: String,
pub db_user: String,
pub db_password: String,
pub db_pool_size: usize,
/// 内部服务调用密钥PHP注册服务、上链服务使用
pub internal_api_key: String,
}
impl AppConfig {
pub fn from_env() -> Result<Self, String> {
Ok(AppConfig {
host: env::var("WALLET_HOST").unwrap_or_else(|_| "127.0.0.1".to_string()),
port: env::var("WALLET_PORT")
.unwrap_or_else(|_| "8701".to_string())
.parse()
.map_err(|_| "WALLET_PORT必须是有效端口号")?,
jwt_secret: env::var("JWT_SECRET")
.map_err(|_| "JWT_SECRET环境变量未设置")?,
admin_jwt_secret: env::var("ADMIN_JWT_SECRET")
.map_err(|_| "ADMIN_JWT_SECRET环境变量未设置")?,
db_host: env::var("PG_HOST").unwrap_or_else(|_| "127.0.0.1".to_string()),
db_port: env::var("PG_PORT")
.unwrap_or_else(|_| "5432".to_string())
.parse()
.map_err(|_| "PG_PORT必须是有效端口号")?,
db_name: env::var("PG_DBNAME").unwrap_or_else(|_| "nac_wallet".to_string()),
db_user: env::var("PG_USER").unwrap_or_else(|_| "nac_wallet_user".to_string()),
db_password: env::var("PG_PASSWORD")
.map_err(|_| "PG_PASSWORD环境变量未设置")?,
db_pool_size: env::var("DB_POOL_SIZE")
.unwrap_or_else(|_| "10".to_string())
.parse()
.unwrap_or(10),
internal_api_key: env::var("INTERNAL_API_KEY")
.map_err(|_| "INTERNAL_API_KEY环境变量未设置")?,
})
}
}
/// 创建PostgreSQL连接池
pub async fn create_db_pool(config: &AppConfig) -> Result<Pool, String> {
let mut pg_config = PgConfig::new();
pg_config.host = Some(config.db_host.clone());
pg_config.port = Some(config.db_port);
pg_config.dbname = Some(config.db_name.clone());
pg_config.user = Some(config.db_user.clone());
pg_config.password = Some(config.db_password.clone());
let mut pool_config = deadpool_postgres::PoolConfig::new(config.db_pool_size);
pool_config.timeouts.wait = Some(std::time::Duration::from_secs(5));
pg_config.pool = Some(pool_config);
pg_config
.create_pool(Some(Runtime::Tokio1), NoTls)
.map_err(|e| format!("数据库连接池创建失败: {}", e))
}