Procházet zdrojové kódy

示例第二版,可以解决core跨包引用的问题。

skyfffire před 1 rokem
rodič
revize
e11cab47e0
1 změnil soubory, kde provedl 32 přidání a 17 odebrání
  1. 32 17
      tests/framework_3_0_test.rs

+ 32 - 17
tests/framework_3_0_test.rs

@@ -7,26 +7,36 @@ use tracing::info;
 use global::log_utils::init_log_with_info;
 
 
-struct Node {
+struct Core {
     pub count: u128
 }
 
 #[tokio::test]
-async fn main() {
+async fn framework_3_0() {
     init_log_with_info();
 
-    let node = Arc::new(Mutex::new(Node { count: 0 }));
+    let core = Arc::new(Mutex::new(Core { count: 0 }));
+    let handler_am = Arc::new(Mutex::new(TestHandler { core_am: core }));
 
-    generator(handle, node).await;
+    // 一个闭包解决了引用问题。
+    generator(|data| {
+        let handler_c = handler_am.clone();
+
+        async move {
+            let mut handler = handler_c.lock().await;
+
+            handler.on_data(data).await
+        }
+    }).await;
 }
 
 // 消息创造者
-async fn generator<F, Fut>(handle_function: F, node: Arc<Mutex<Node>>)
+async fn generator<F, Fut>(handle_function: F)
 where
-    F: Fn(Arc<Mutex<Node>>, ResponseData) -> Fut,
+    F: Fn(ResponseData) -> Fut,
     Fut: Future<Output = ()> + Send + 'static, // 确保 Fut 是一个 Future,且输出类型为 ()
 {
-    let mut data = ResponseData::new("aaa".to_string(),
+    let data = ResponseData::new("aaa".to_string(),
                                  "code".to_string(),
                                  "msg".to_string(),
                                  "data".to_string());
@@ -34,20 +44,25 @@ where
         let mut s_data = data.clone();
         s_data.time = chrono::Utc::now().timestamp_micros();
 
-        handle_function(node.clone(), s_data).await;
+        handle_function(s_data).await;
 
         tokio::time::sleep(Duration::from_micros(100)).await;
     }
 }
 
-// 消息处理者
-async fn handle(node: Arc<Mutex<Node>>, data: ResponseData) {
-    let mut node = node.lock().await;
-    // 实现您的处理逝剧
-    // 例如,增加计数:
-    node.count += 1;
-    let delay = chrono::Utc::now().timestamp_micros() - data.time;
-    // 处理响应数据
-    info!("Handled data: {}, count is: {}, delay is: {}.", data.data, node.count, delay);
+struct TestHandler {
+    pub core_am: Arc<Mutex<Core>>
 }
 
+impl TestHandler {
+    // 消息处理者
+    pub async fn on_data(&mut self, data: ResponseData) {
+        let mut core = self.core_am.lock().await;
+        // 实现您的处理逝剧
+        // 例如,增加计数:
+        core.count += 1;
+        let delay = chrono::Utc::now().timestamp_micros() - data.time;
+        // 处理响应数据
+        info!("Handled data: {}, count is: {}, delay is: {}.", data.data, core.count, delay);
+    }
+}