在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
以下是官方文档的学习,了解基本的actix actor 编程模型 项目初始化
cargo new actor-ping --bin
├── Cargo.toml
└── src
└── main.rs
添加依赖
[package]
name = "actor-ping"
version = "0.1.0"
authors = ["rongfengliang <[email protected]>"]
edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
actix = "0.8"
创建Actor trait
use actix::prelude::*;
struct MyActor {
count: usize,
}
impl Actor for MyActor {
type Context = Context<Self>;
}
说明 定义消息消息是actor 可以接受的数据,消息是任何实现 use actix::prelude::*;
struct Ping(usize);
impl Message for Ping {
type Result = usize;
}
定义消息的handlerhandler 是能处理对应消息实现了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 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 |
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论