actix rust actor 框架學習 二 ping actor demo 代碼


以下是官方文檔的學習,了解基本的actix actor 編程模型

項目初始化

  • cargo 創建
cargo new actor-ping --bin
  • 效果
├── Cargo.toml
└── src
    └── main.rs

添加依賴

  • cargo.toml 配置
[package]
name = "actor-ping"
version = "0.1.0"
authors = ["rongfengliang <1141591465@qq.com>"]
edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
actix = "0.8"

創建Actor trait

  • actor 代碼
use actix::prelude::*;
struct MyActor {
    count: usize,
}
impl Actor for MyActor {
    type Context = Context<Self>;
}
 

說明
每個actor 必須有一個context,后邊會有介紹

定義消息

消息是actor 可以接受的數據,消息是任何實現Message trait 的類型

use actix::prelude::*;
struct Ping(usize);
impl Message for Ping {
    type Result = usize;
}
 
 

定義消息的handler

handler 是能處理對應消息實現了Handler trait 的方法

impl Handler<Ping> for MyActor {
    type Result = usize;
    fn handle(&mut self, msg: Ping, _ctx: &mut Context<Self>) -> Self::Result {
        self.count += msg.0;
        self.count
    }
}

啟動actor 以及處理效果

啟動actor 依賴context,上邊demo 使用的Context 依賴的基於tokio/future 的context
所以可以使用Actor::start()或者Actor::create(),我們可以使用do_send 發送不需要等待響應
的消息,或者使用send 發送特定消息,start() 以及creat() 都返回一個adress 對象

 
fn main() -> std::io::Result<()> {
    let system = System::new("test");
    // start new actor
    let addr = MyActor{count: 10}.start();
    // send message and get future for result
    let res = addr.send(Ping(10));
    Arbiter::spawn(
        res.map(|res| {
            println!("RESULT: {}", res == 20);
        })
        .map_err(|_| ()));
    system.run()
}

運行&&效果

  • 運行
cargo run
  • 效果

 

 

參考資料

https://actix.rs/book/actix/sec-1-getting-started.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM