Rust通用功能库eva-common的使用,提供高效跨平台基础组件与实用工具集

Rust通用功能库eva-common的使用,提供高效跨平台基础组件与实用工具集

概述

EVA ICS v4 commons是一个包含通用类型和功能的Rust库,用于EVA ICS v4、EVA ICS v4 SDK以及自定义应用程序开发。

安装

在项目目录中运行以下Cargo命令:

cargo add eva-common

或者在Cargo.toml中添加以下行:

eva-common = "0.3.107"

示例代码

以下是一个使用eva-common库的完整示例:

use eva_common::prelude::*;

fn main() -> Result<(), Error> {
    // 创建一个新的配置对象
    let config = Config::new();
    
    // 设置配置参数
    config.set("key", "value")?;
    
    // 获取配置参数
    if let Some(value) = config.get("key") {
        println!("Config value: {}", value);
    }
    
    // 使用日志功能
    info!("This is an info message");
    warn!("This is a warning message");
    error!("This is an error message");
    
    // 使用错误处理
    let result = some_operation();
    if let Err(e) = result {
        error!("Operation failed: {}", e);
        return Err(e);
    }
    
    Ok(())
}

fn some_operation() -> Result<(), Error> {
    // 模拟一个可能失败的操作
    if rand::random() {
        Ok(())
    } else {
        Err(Error::failed("Operation failed randomly"))
    }
}

完整示例demo

以下是一个更完整的eva-common使用示例,展示了更多功能:

use eva_common::prelude::*;
use std::time::Duration;

// 自定义错误类型
#[derive(Debug)]
struct CustomError;

impl std::fmt::Display for CustomError {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "Custom error occurred")
    }
}

impl std::error::Error for CustomError {}

fn main() -> Result<(), Error> {
    // 初始化日志系统
    init_logger();
    
    // 创建并配置应用
    let mut app = Application::new("demo_app")
        .version("1.0.0")
        .description("EVA Common Demo Application");
    
    // 添加命令行参数
    app.arg("config", "Configuration file path", Some("config.toml"));
    
    // 解析命令行参数
    let args = app.parse_args();
    let config_file = args.get("config").unwrap();
    
    // 加载配置文件
    let config = Config::from_file(config_file)?;
    
    // 获取配置值
    let timeout = config.get_as::<u64>("timeout").unwrap_or(30);
    info!("Timeout set to {} seconds", timeout);
    
    // 使用异步任务
    let rt = Runtime::new()?;
    rt.block_on(async {
        // 执行异步操作
        match perform_async_task(timeout).await {
            Ok(result) => info!("Task completed with result: {}", result),
            Err(e) => error!("Async task failed: {}", e),
        }
    });
    
    Ok(())
}

async fn perform_async_task(timeout: u64) -> Result<String, Error> {
    // 模拟异步任务
    tokio::time::sleep(Duration::from_secs(timeout)).await;
    
    if rand::random() {
        Ok("Success".to_string())
    } else {
        Err(Error::failed("Random failure in async task"))
    }
}

fn init_logger() {
    // 配置日志系统
    LoggerBuilder::new()
        .level(LogLevel::Info)
        .output(LogOutput::Stdout)
        .format(LogFormat::Default)
        .init()
        .expect("Failed to initialize logger");
}

功能特性

eva-common库提供以下主要功能:

  1. 通用类型定义
  2. 错误处理机制
  3. 配置管理
  4. 日志记录
  5. 跨平台支持

许可证

该项目使用Apache-2.0许可证。

维护者

  • Sergiy S. (divi255)
  • YB (yblokh)

1 回复

Rust通用功能库eva-common使用指南

概述

eva-common是一个Rust编写的通用功能库,提供了一系列高效跨平台的基础组件和实用工具集。它旨在简化Rust开发中的常见任务,提高开发效率,同时保持高性能和跨平台兼容性。

主要功能

  1. 跨平台文件系统操作
  2. 高性能日志记录
  3. 常用数据结构扩展
  4. 网络工具
  5. 并发编程辅助工具
  6. 配置管理
  7. 错误处理工具

安装方法

在Cargo.toml中添加依赖:

[dependencies]
eva-common = "0.3"  # 请使用最新版本

使用示例

1. 文件系统操作

use eva_common::fs::{ensure_dir, read_file_to_string};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    // 确保目录存在
    ensure_dir("/tmp/example_dir")?;
    
    // 读取文件内容
    let content = read_file_to_string("Cargo.toml")?;
    println!("File content: {}", content);
    
    Ok(())
}

2. 日志记录

use eva_common::log::{init_logger, LogLevel};

fn main() {
    // 初始化日志记录器
    init_logger(LogLevel::Info).unwrap();
    
    // 记录不同级别的日志
    log::info!("This is an info message");
    log::warn!("This is a warning");
    log::error!("This is an error");
}

3. 并发工具

use eva_common::concurrency::ThreadPool;
use std::sync::Arc;

fn main() {
    // 创建线程池
    let pool = ThreadPool::new(4);
    let counter = Arc::new(std::sync::Mutex::new(0));
    
    for _ in 0..10 {
        let counter = Arc::clone(&counter);
        pool.execute(move || {
            let mut num = counter.lock().unwrap();
            *num += 1;
        });
    }
    
    // 等待所有任务完成
    pool.join();
    println!("Final counter value: {}", *counter.lock().unwrap());
}

4. 配置管理

use eva_common::config::{Config, ConfigError};

#[derive(Debug, Default)]
struct AppConfig {
    port: u16,
    host: String,
    debug_mode: bool,
}

impl Config for AppConfig {
    fn from_file(path: &str) -> Result<self, ConfigError> {
        // 实现从文件加载配置
        // ...
    }
}

fn main() -> Result<(), ConfigError> {
    let config = AppConfig::from_file("config.toml")?;
    println!("Loaded config: {:?}", config);
    Ok(())
}

5. 错误处理

use eva_common::error::{Error, ResultExt};

fn fallible_operation() -> Result<(), Error> {
    // 可能失败的操作
    std::fs::File::open("nonexistent.txt")
        .chain_err(|| "Failed to open file")?;
    Ok(())
}

fn main() {
    if let Err(e) = fallible_operation() {
        eprintln!("Error occurred: {}", e);
        if let Some(inner) = e.source() {
            eprintln!("Caused by: {}", inner);
        }
    }
}

高级特性

自定义日志格式

use eva_common::log::{init_custom_logger, LogFormat};

fn main() {
    init_custom_logger(
        LogLevel::Debug,
        LogFormat::Custom("{level} - {message} [{file}:{line}]"),
    ).unwrap();
    
    log::debug!("Custom format log message");
}

性能监控

use eva_common::performance::{measure_time, MeasureResult};

fn expensive_operation() {
    // 模拟耗时操作
    std::thread::sleep(std::time::Duration::from_millis(100));
}

fn main() {
    let MeasureResult { duration, .. } = measure_time(|| expensive_operation());
    println!("Operation took {} ms", duration.as_millis());
}

最佳实践

  1. 对于文件系统操作,优先使用eva-common提供的跨平台版本
  2. 在应用程序启动时尽早初始化日志系统
  3. 利用提供的错误处理工具来构建清晰的错误链
  4. 对于CPU密集型任务,使用内置的线程池而非直接创建线程
  5. 配置管理应遵循库提供的Config trait实现

注意事项

  1. 某些功能可能需要特定的平台支持
  2. 在生产环境中使用前,请充分测试性能影响
  3. 定期检查库的更新,以获取性能改进和新功能
  4. 某些高级功能可能需要额外的特性标志启用

通过eva-common,开发者可以专注于业务逻辑而非基础设施代码,同时保持代码的高性能和可维护性。

完整示例demo

文件系统操作完整示例

use eva_common::fs::{ensure_dir, create_file, read_file_to_string, remove_file};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    // 确保目录存在
    let dir_path = "/tmp/eva_example";
    ensure_dir(dir_path)?;
    println!("Directory ensured: {}", dir_path);
    
    // 创建文件
    let file_path = format!("{}/test.txt", dir_path);
    create_file(&file_path, "Hello eva-common!")?;
    println!("File created: {}", file_path);
    
    // 读取文件
    let content = read_file_to_string(&file_path)?;
    println!("File content: {}", content);
    
    // 清理文件
    remove_file(&file_path)?;
    println!("File removed: {}", file_path);
    
    Ok(())
}

日志系统完整示例

use eva_common::log::{init_custom_logger, LogLevel, LogFormat};

mod business {
    pub fn process_data() {
        log::info!("Processing data...");
        // 模拟业务逻辑
        std::thread::sleep(std::time::Duration::from_millis(50));
        log::warn!("Data processing took longer than expected");
    }
}

fn main() {
    // 初始化自定义日志格式
    init_custom_logger(
        LogLevel::Debug,
        LogFormat::Custom("[{time}] {level} - {message} (at {file}:{line})"),
    ).unwrap();
    
    log::debug!("Application starting");
    business::process_data();
    log::error!("Simulated error occurred");
    log::debug!("Application shutting down");
}

线程池与性能监控完整示例

use eva_common::concurrency::ThreadPool;
use eva_common::performance::{measure_time, MeasureResult};
use std::sync::{Arc, Mutex};

fn expensive_task(id: usize, shared_counter: Arc<Mutex<u32>>) {
    // 模拟耗时任务
    std::thread::sleep(std::time::Duration::from_millis(100));
    
    let mut num = shared_counter.lock().unwrap();
    *num += 1;
    
    println!("Task {} completed, counter: {}", id, *num);
}

fn main() {
    // 创建线程池
    let pool = ThreadPool::new(4);
    let counter = Arc::new(Mutex::new(0));
    
    // 测量性能
    let MeasureResult { duration, .. } = measure_time(|| {
        for i in 0..10 {
            let counter = Arc::clone(&counter);
            pool.execute(move || {
                expensive_task(i, counter);
            });
        }
        
        // 等待所有任务完成
        pool.join();
    });
    
    println!("All tasks completed in {} ms", duration.as_millis());
    println!("Final counter value: {}", *counter.lock().unwrap());
}

配置管理完整示例

use eva_common::config::{Config, ConfigError};
use serde::{Deserialize, Serialize};
use std::path::Path;

#[derive(Debug, Serialize, Deserialize, Default)]
struct AppConfig {
    server_port: u16,
    db_url: String,
    enable_cache: bool,
}

impl Config for AppConfig {
    fn from_file(path: &str) -> Result<Self, ConfigError> {
        // 读取配置文件
        let config_str = std::fs::read_to_string(path)?;
        
        // 根据文件扩展名决定解析方式
        match Path::new(path).extension().and_then(|s| s.to_str()) {
            Some("json") => serde_json::from_str(&config_str)
                .map_err(|e| ConfigError::ParseError(e.to_string())),
            Some("toml") => toml::from_str(&config_str)
                .map_err(|e| ConfigError::ParseError(e.to_string())),
            _ => Err(ConfigError::UnsupportedFormat),
        }
    }
}

fn main() -> Result<(), ConfigError> {
    // 示例配置文件内容
    let config_content = r#"
        server_port = 8080
        db_url = "postgres://user:pass@localhost/db"
        enable_cache = true
    "#;
    
    // 创建临时配置文件
    let config_path = "config.toml";
    std::fs::write(config_path, config_content)?;
    
    // 加载配置
    let config = AppConfig::from_file(config_path)?;
    println!("Loaded config: {:?}", config);
    
    // 清理临时文件
    std::fs::remove_file(config_path)?;
    
    Ok(())
}

综合应用示例

use eva_common::{
    fs::{ensure_dir, read_file_to_string},
    log::{init_logger, LogLevel},
    error::{Error, ResultExt},
    concurrency::ThreadPool,
    performance::measure_time,
};
use std::sync::{Arc, Mutex};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    // 初始化日志
    init_logger(LogLevel::Debug)?;
    
    // 文件操作
    ensure_dir("/tmp/eva_integration")?;
    log::info!("Directory ensured");
    
    // 性能监控下的并发处理
    let pool = ThreadPool::new(2);
    let counter = Arc::new(Mutex::new(0));
    
    let MeasureResult { duration, .. } = measure_time(|| {
        for i in 0..5 {
            let counter = Arc::clone(&counter);
            pool.execute(move || {
                let mut num = counter.lock().unwrap();
                *num += 1;
                log::debug!("Task {} completed, counter: {}", i, *num);
            });
        }
        pool.join();
    });
    
    log::info!("All tasks completed in {}ms", duration.as_millis());
    
    // 错误处理示例
    let result = read_file_to_string("nonexistent.file")
        .chain_err(|| "Failed to read file");
    
    if let Err(e) = result {
        log::error!("{}", e);
        if let Some(inner) = e.source() {
            log::error!("Caused by: {}", inner);
        }
    }
    
    Ok(())
}
回到顶部