#actor-model #actor-framework #tokio #otp #erlang #message #high-level

linkd

一个简单的actor模型框架,灵感来源于Erlang生态系统中的OTP。

4个版本

0.1.3 2024年5月25日
0.1.2 2024年5月25日
0.1.1 2023年11月28日
0.1.0 2023年11月24日

744异步

Download history 247/week @ 2024-05-24 15/week @ 2024-05-31 6/week @ 2024-06-07

每月 156 下载

MIT 许可证

9KB
153

Linkd

一个简单的轻量级actor模型框架,灵感来源于Erlang生态系统中的OTP。

Linkd更注重高级功能。它假设你在异步tokio运行时中调用它。

入门

你的actor需要定义三个部分

  • 内部状态的类型和初始值。
  • 所有传入消息的类型。
  • 所有可能响应的类型。

然后实现你的消息类型的处理程序,这样就完成了。

以下是一个简单的actor,它可以接收ping消息,并响应pong。

use async_trait::async_trait;
use linkd::{Actor, Handler};

type HealthActor = Actor::<MyState, Messages, Responses>;

struct MyState;

enum Messages {
    Ping,
}

enum Responses {
    Pong,
}

#[async_trait]
impl Handler<MyState, Responses> for Messages {
    async fn handle(&self, _state: &mut MyState) -> Responses {
        match self {
            Messages::Ping => {
                println!("Hello darkness my old friend.");

                Responses::Pong
            }
        }
    }
}


#[tokio::main]
async fn main() {

    // Create a registry(optional)
    let mut registry = Registry::new();

    // Initialize the actor and immediately start it up
    let mut my_actor = HealthActor::new();
    my_actor.startup(MyState {}).await;
    // Move the actor to the registry
    my_actor.register(&mut registry);
  

    // Go fetch the actor out of the registry from anywhere.
    let local_ref = HealthActor::fetch_from_registry(&registry);

    // Call out to the actor and wait for a response.
    let response = local_ref.call(Messages::Ping).await;
    
    if response == Responses::Pong {
        println!("Would you look at that!");
    }

    // Cast a message to the actor. This is akin to a fire and forget.
    local_ref.cast(Messages::V4).await;
}

依赖关系

~2.3–4MB
~64K SLoC