| Crates.io | config_rw |
| lib.rs | config_rw |
| version | 2.1.1 |
| created_at | 2025-07-08 07:04:30.70592+00 |
| updated_at | 2026-01-14 14:03:19.195955+00 |
| description | 配置文件读取与写入 |
| homepage | |
| repository | |
| max_upload_size | |
| id | 1742150 |
| size | 172,326 |
Thread-safe Configuration Management Library with Read/Write and Auto Hot-Reload
线程安全的配置管理库,支持读写操作及自动热重载
Read & Write Config | 配置读写
Type-safe access (String, Integer, Float, Bool, JSON) with auto-save capability.
类型安全的访问(支持字符串、整数、浮点、布尔、JSON),更改会自动保存到文件。
Auto Callback on External Change | 外部变更自动回调
Register callbacks that are automatically triggered when the file is modified externally.
注册回调函数,当文件被外部进程修改时会自动触发,无需手动轮询。
Thread Safety | 线程安全
Safe for concurrent access using Arc and RwLock.
基于 Arc 和 RwLock 保证并发访问安全。
Add to Cargo.toml | 添加到 Cargo.toml:
[dependencies]
config_rw = "2.1.0"
use std::sync::LazyLock;
use config_rw::ConfigState;
// Initialize global config instance
// 初始化全局配置实例
static CONFIG: LazyLock<ConfigState> = LazyLock::new(|| {
ConfigState::init_config("config.toml")
});
fn main() -> Result<(), Box<dyn std::error::Error>> {
// 1. Register Auto-Callback for External Changes
// Triggered automatically when file is modified externally
// 1. 注册外部变更自动回调
// 当文件被外部进程修改时自动触发
CONFIG.add_change_callback(|| {
let new_val = CONFIG.get_string("app.name").unwrap_or_default();
println!("📝 Config auto-reloaded! app.name: {}", new_val);
});
// 2. Write Configuration (Thread-safe & Auto-saved)
// Internal writes do NOT trigger the callback
// 2. 写入配置(线程安全且自动保存)
// 程序内部写入不会触发回调
CONFIG.set_string("app.name", "MyApplication".to_string())?;
CONFIG.set_i64("server.port", 8080)?;
// 3. Read Configuration
// 3. 读取配置
let app_name = CONFIG.get_string("app.name").unwrap_or_default();
println!("📖 App Name: {}", app_name);
// Keep running - callbacks fire automatically on file changes
// 保持运行 - 文件变化时回调会自动触发
loop {
std::thread::sleep(std::time::Duration::from_secs(1));
}
}
get_string("key") → Option<String>get_i64("key") → Option<i64>get_bool("key") → Option<bool>get_value("key") → Value (serde_json)set_string("key", val) → Result<()>set_i64("key", val) → Result<()>set_bool("key", val) → Result<()>init_config("path") → Initialize / 初始化add_change_callback(Fn()) → Auto-triggered on external file changes / 外部文件变更时自动触发MIT / Apache-2.0