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

posted on   荣锋亮  阅读(933)  评论(0编辑  收藏  举报

编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
历史上的今天:
2019-01-18 gearman openresty 集成试用
2019-01-18 madlib 集成 hasura graphql-engine 试用
2019-01-18 gearman kubernetes 运行
2019-01-18 gearman 简单试用
2014-01-18 smarty学习——内建函数 部分
2014-01-18 smarty学习——组合修改器
2014-01-18 smarty学习——变量调节器(过滤器)

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示