Module ractor::registry

source ·
Expand description

Represents an actor registry.

It allows unique naming of actors via String so it works more or less like an Erlang atom()

Actors are automatically registered into the global registry, if they provide a name, upon construction.Actors are also automatically unenrolled from the registry upon being dropped, therefore freeing the name for subsequent registration.

You can then retrieve actors by name with where_is. Note: this function only returns the ActorCell reference to the actor, it additionally requires knowledge of the crate::Actor in order to send messages to it (since you need to know the message type) or agents will runtime panic on message reception, and supervision processes would need to restart the actors.

§Examples

Basic actor retrieval

async fn test() {
    let maybe_actor = ractor::registry::where_is("my_actor".to_string());
    if let Some(actor) = maybe_actor {
        // send a message, or interact with the actor
        // but you'll need to know the actor's strong type
    }
}

Full example

use ractor::registry;
use ractor::{Actor, ActorProcessingErr, ActorRef};

struct ExampleActor;

#[cfg_attr(feature = "async-trait", ractor::async_trait)]
impl Actor for ExampleActor {
    type Msg = ();
    type State = ();
    type Arguments = ();

    async fn pre_start(
        &self,
        _myself: ActorRef<Self::Msg>,
        _args: Self::Arguments,
    ) -> Result<Self::State, ActorProcessingErr> {
        println!("Starting");
        Ok(())
    }
}

#[tokio::main]
async fn main() {
    let (actor, handle) = Actor::spawn(Some("my_actor".to_string()), ExampleActor, ())
        .await
        .expect("Failed to startup dummy actor");

    // Retrieve the actor by name from the registry
    let who: ActorRef<()> = registry::where_is("my_actor".to_string())
        .expect("Failed to find actor")
        .into();
    who.cast(()).expect("Failed to send message");

    // wait for actor exit
    actor.stop(None);
    handle.await.unwrap();

    // Automatically removed from the registry upon shutdown
    assert!(registry::where_is("my_actor".to_string()).is_none());
}

Enums§

Functions§

  • Returns a list of names that have been registered
  • Try and retrieve an actor from the registry