Actix Actor
Actor
Actor 创建并发送和接收消息
Actor实现、Message实现
#![allow(unused)] fn main() { use actix::{Actor, Context, Message, Handler, dev::MessageResponse}; struct MyActor{ count:usize } /// /// Actor impl Actor for MyActor { // 每个actor都有一个context type Context = Context<Self>; } #[derive(Message)] #[rtype(result = "usize")] struct Ping(usize); impl Handler<Ping> for MyActor { type Result = usize; /// /// 接受Ping类型的消息 然后返回usize fn handle(&mut self, msg: Ping, ctx: &mut Self::Context) -> Self::Result { self.count += msg.0; self.count } } }
发送,接收处理
#![allow(unused)] fn main() { #[actix::test] async fn test1(){ // 开启新的actor并且返回地址也就近似于akka 中的 ActorRef let addr = MyActor { count:10}.start(); // send 然后handler处理返回 let res = addr.send(Ping(10)).await; print!("Res : {}\n",res.unwrap()); let id = System::current().id(); print!("id:{} will stop",id); System::current().stop(); } }
生命周期函数
#![allow(unused)] fn main() { /// /// 生命周期有 /// + Started /// + Running /// + Stopping /// + Stopped /// /// 重写生命周期函数started,stopped impl Actor for MineActor { type Context = Context<Self>; fn started(&mut self, ctx: &mut Self::Context) { println!("started"); } fn stopped(&mut self, ctx: &mut Self::Context) { println!("stopped") } } }
可Response的Message
#![allow(unused)] fn main() { /// /// 为了可以返回Responses 我们为Responses实现MessageResponse impl<A,M> MessageResponse<A,M> for Responses where A:Actor, M:Message<Result = Responses> { fn handle(self, ctx: &mut <A as Actor>::Context, tx: Option<actix::dev::OneshotSender<<M as Message>::Result>>) { if let Some(tx) = tx { tx.send(self); } } } }