Rust의 배우 프레임 워크
Any ) actix 사용하려면 Cargo.toml 에 이것을 추가하십시오.
[ dependencies ]
actix = " 0.13 " Actix를 사용하려면 먼저 System 만들어야합니다.
fn main ( ) {
let system = actix :: System :: new ( ) ;
system . run ( ) ;
} Actix는 Tokio 런타임을 사용합니다. System::new() 새로운 이벤트 루프를 만듭니다. System.run() Tokio Event Loop을 시작하고 System 메시지 SystemExit 수신하면 완료됩니다.
배우를 정의하려면 구조물을 정의하고 Actor 특성을 구현해야합니다.
use actix :: { Actor , Context , System } ;
struct MyActor ;
impl Actor for MyActor {
type Context = Context < Self > ;
fn started ( & mut self , _ctx : & mut Self :: Context ) {
println ! ( "I am alive!" ) ;
System :: current ( ) . stop ( ) ; // <- stop system
}
}
fn main ( ) {
let system = System :: new ( ) ;
let _addr = system . block_on ( async { MyActor . start ( ) } ) ;
system . run ( ) . unwrap ( ) ;
} 새로운 배우를 때리기 start 하고 배우 특성의 방법을 create . 배우를 만드는 몇 가지 방법을 제공합니다. 자세한 내용은 문서를 확인하십시오. 배우 특성의 started , stopping 및 stopped 방법을 구현할 수 있습니다. 배우가 시작하고 배우가 끝나면 stopping started 됩니다. 액터 라이프 사이클에 대한 자세한 내용은 API 문서를 확인하십시오.
배우는 메시지를 보내서 다른 배우와 의사 소통합니다. Actix에서는 모든 메시지가 입력됩니다. 두 개의 usize 매개 변수와이 메시지를 받아들이고이 두 숫자의 합을 반환하는 액터로 간단한 Sum 메시지를 정의해 봅시다. 여기서 우리는 #[actix::main] 속성을 System 시작하고 기본 기능을 구동하는 더 쉬운 방법으로 사용하여 Actor 로부터 전송 된 응답을 쉽게 .await .
use actix :: prelude :: * ;
// this is our Message
// we have to define the response type (rtype)
# [ derive ( Message ) ]
# [ rtype ( usize ) ]
struct Sum ( usize , usize ) ;
// Actor definition
struct Calculator ;
impl Actor for Calculator {
type Context = Context < Self > ;
}
// now we need to implement `Handler` on `Calculator` for the `Sum` message.
impl Handler < Sum > for Calculator {
type Result = usize ; // <- Message response type
fn handle ( & mut self , msg : Sum , _ctx : & mut Context < Self > ) -> Self :: Result {
msg . 0 + msg . 1
}
}
# [ actix :: main ] // <- starts the system and block until future resolves
async fn main ( ) {
let addr = Calculator . start ( ) ;
let res = addr . send ( Sum ( 10 , 5 ) ) . await ; // <- send message and get future for result
match res {
Ok ( result ) => println ! ( "SUM: {}" , result ) ,
_ => println ! ( "Communication to the actor has failed" ) ,
}
} 액터와의 모든 커뮤니케이션은 Addr 객체를 통과합니다. 응답을 기다리지 않고 do_send 를 할 수 있거나 액터에게 특정 메시지를 send 수 있습니다. Message 특성은 메시지의 결과 유형을 정의합니다.
Actor 와 Handler 특성의 방법이 &mut self 받아들이는 것을 알 수 있으므로 배우에 무엇이든 저장하고 필요할 때마다 돌연변이 할 수 있습니다.
주소 객체에는 액터 유형이 필요하지만 메시지를 처리 할 수있는 액터에게 특정 메시지를 보내려면 Recipient 인터페이스를 사용할 수 있습니다. Recipient 사용하는 새로운 배우를 만들어 봅시다.
use actix :: prelude :: * ;
use std :: time :: Duration ;
# [ derive ( Message ) ]
# [ rtype ( result = "()" ) ]
struct Ping {
pub id : usize ,
}
// Actor definition
struct Game {
counter : usize ,
name : String ,
recipient : Recipient < Ping > ,
}
impl Actor for Game {
type Context = Context < Game > ;
}
// simple message handler for Ping message
impl Handler < Ping > for Game {
type Result = ( ) ;
fn handle ( & mut self , msg : Ping , ctx : & mut Context < Self > ) {
self . counter += 1 ;
if self . counter > 10 {
System :: current ( ) . stop ( ) ;
} else {
println ! ( "[{0}] Ping received {1}" , self . name , msg . id ) ;
// wait 100 nanoseconds
ctx . run_later ( Duration :: new ( 0 , 100 ) , move |act , _| {
act . recipient . do_send ( Ping { id : msg . id + 1 } ) ;
} ) ;
}
}
}
fn main ( ) {
let system = System :: new ( ) ;
system . block_on ( async {
// To create a cyclic game link, we need to use a different constructor
// method to get access to its recipient before it starts.
let _game = Game :: create ( |ctx| {
// now we can get an address of the first actor and create the second actor
let addr = ctx . address ( ) ;
let addr2 = Game {
counter : 0 ,
name : String :: from ( "Game 2" ) ,
recipient : addr . recipient ( ) ,
}
. start ( ) ;
// let's start pings
addr2 . do_send ( Ping { id : 10 } ) ;
// now we can finally create first actor
Game {
counter : 0 ,
name : String :: from ( "Game 1" ) ,
recipient : addr2 . recipient ( ) ,
}
} ) ;
} ) ;
// let the actors all run until they've shut themselves down
system . run ( ) . unwrap ( ) ;
}네트워킹 클라이언트/서버 서비스에서보다 포괄적 인 사용을 보여주는이 채팅 예제를 참조하십시오.
기능 요청이 있으면 모든 기부금을 환영합니다. 주저하지 말고 문제를 열지 마십시오!
이 프로젝트는 중 하나에 따라 라이센스가 부여됩니다
귀하의 선택에.
Actix Repo에 대한 기여는 기고자 언약의 조건에 따라 구성됩니다. Actix 팀은 해당 행동 강령을지지하기 위해 개입 할 것을 약속합니다.