13个稳定版本
1.3.1 | 2024年1月19日 |
---|---|
1.2.9 | 2024年1月19日 |
1.2.5 | 2023年12月21日 |
1.2.1 | 2023年9月8日 |
0.1.2 | 2023年8月20日 |
#12 in #lifecycle
每月 128 次下载
27KB
199 代码行
Actorlib
确实,这是一个actor库,而不是框架,用Rust编写
功能
- 异步发送消息
- 异步处理actor中的消息
- 支持发送和忘记的消息
- 支持发送并等待响应的消息
- actor的可变状态
- actor从上下文中进行自我引用
- actor生命周期(pre_start, pre_stop)
用法
Cargo.toml
[dependencies]
actorlib = "1.3.1"
echo.rs
#[derive(Debug)]
pub struct Echo;
#[derive(Debug)]
pub enum Message {
Ping,
}
#[derive(Debug)]
pub enum Response {
Pong {counter: u32},
}
#[derive(Debug,Clone)]
pub struct State {
pub counter: u32,
}
#[derive(Debug, Error)]
pub enum EchoError {
#[error("unknown error")]
Unknown,
#[error("std::io::Error")]
StdErr(#[from] std::io::Error),
}
#[async_trait]
impl Handler<Echo, Message, State, Response, EchoError> for Echo {
async fn receive(&self, ctx: Arc<Context<Echo, Message, State, Response, EchoError>>) -> Result<Response, EchoError> {
match ctx.mgs {
Message::Ping => {
println!("Received Ping");
let mut state_lock = ctx.state.lock().await;
state_lock.counter += 1;
if state_lock.counter > 10 {
Err(EchoError::Unknown)
} else {
Ok(Response::Pong{counter: state_lock.counter})
}
}
}
}
}
main.rs
#[tokio::main]
async fn main() -> Result<(), EchoError> {
let state = State {
counter: 0,
};
let echo_ref = ActorRef::new("echo".to_string(), Echo{}, state, 100000).await?;
println!("Sent Ping");
echo_ref.send(Message::Ping).await?;
println!("Sent Ping and ask response");
let pong = echo_ref.ask(Message::Ping).await?;
println!("Got {:?}", pong);
_ = echo_ref.stop();
tokio::time::sleep(Duration::from_millis(1000)).await;
Ok(())
}
示例输出
Sent Ping
Sent Ping and ask response
Received Ping
Received Ping
Got Pong { counter: 2 }
示例源代码: https://github.com/evgenyigumnov/actor-lib/tree/main/test
依赖项
~3–10MB
~92K SLoC