| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849 |
- use tokio::fs::File;
- use tokio::io::AsyncWriteExt;
- use tokio::{fs, spawn};
- use tracing::{error};
- pub fn write_to_file(json_data: String, file_path: String) {
- spawn(async move {
- // 尝试创建文件路径
- if let Err(e) = fs::create_dir_all(
- // 获取文件目录路径
- std::path::Path::new(&file_path)
- .parent() // 获取父目录(即文件路径除去文件名后的部分)
- .unwrap_or_else(|| std::path::Path::new("")), // 如果没有父目录,使用当前目录
- )
- .await
- {
- // 如果创建路径失败,打印错误日志
- error!("创建目录错误: {:?}", e);
- return; // 结束任务
- }
- // 异步地执行文件写入操作
- if let Err(e) = async {
- let mut file = File::create(&file_path).await?;
- file.write_all(json_data.as_bytes()).await?;
- Result::<(), std::io::Error>::Ok(())
- }
- .await
- {
- // 如果发生错误,只打印错误日志
- error!("json db写入错误: {:?}", e);
- }
- });
- }
- pub fn generate_file_path(exchange: &str, symbol: &str, subscriber_type: &str, serial: i64) -> String {
- return format!("db/{}/{}/{}/{}.json", exchange, symbol, subscriber_type, serial)
- }
- #[tokio::test]
- async fn write_test() {
- use std::time::Duration;
- use tokio::time::sleep;
- // 调用函数,不需要等待它完成
- write_to_file("{\"key\": \"value\"}".to_string(), "db/test.json".to_string());
- sleep(Duration::from_secs(2)).await;
- }
|