Rust 的 Actor 框架。
- 异步和同步actor
- 本地/线程上下文中的 Actor 通信
- 使用期货进行异步消息处理
- Actor 监控
- 类型化的消息(无Any类型)
- 在稳定的 Rust 1.46+ 上运行
使用方法:
在Cargo.toml加入:
[dependencies] actix = "0.12"
|
定义一个actor,你需要定义一个结构体并让它实现Actor trait,通过其start和create方法可以生成新的actor 。它提供了几种不同的创建actor的方法,started,stopping和stopped方法是其生命周期。
use actix::{Actor, Addr, Context, System};
struct MyActor;
impl Actor for MyActor { type Context = Context<Self>;
fn started(&mut self, ctx: &mut Self::Context) { println!("I am alive!"); System::current().stop(); // <- stop system } }
fn main() { let mut system = System::new();
let addr = system.block_on(async { MyActor.start() });
system.run(); }
|
Actix 使用Tokio运行时。System::new()创建一个新的事件循环。System.run()启动 Tokio 事件循环,并在参与者System收到SystemExit消息后结束。
接受消息
Actor 通过发送消息与另一个 Actor 进行通信。use actix::prelude::*;
// this is our Message // we have to define the response type (rtype) #[derive(Message)] #[rtype(result = "usize")] struct Sum(usize, usize);
// Actor definition struct Calculator;
impl Actor for Calculator { type Context = Context<Self>; }
// now we need to implement `Handler` on `Calculator` for the `Sum` message. impl Handler<Sum> for Calculator { type Result = usize; // <- Message response type
fn handle(&mut self, msg: Sum, ctx: &mut Context<Self>) -> Self::Result { msg.0 + msg.1 } }
#[actix::main] // <- starts the system and block until future resolves async fn main() { let addr = Calculator.start(); let res = addr.send(Sum(10, 5)).await; // <- send message and get future for result
match res { Ok(result) => println!("SUM: {}", result), _ => println!("Communication to the actor has failed"), } }
|