[Akka.NET] 액터끼리 메시지 주고 받기

소개

앞에서 서로 다른 액터끼리 메세지를 주고 받는 방법에 대해서 알아 보았습니다.

또한, 부모, 자식끼리 메시지 주고 받는 것도 알아 보았습니다.

이번 포스팅에서는 메시지 마지막 장으로, 나한테 메시지를 보낸 액터를 선택하여 해당 액터에게 다시 새로운 메시지를 보내는 방법에 대해서 알려 드리겠습니다.


예제 코드

  • 나한테 메시지를 보낸 액터에게 다시 메시지를 보내려면 Sender.Tell() 메서드를 이용하면 됩니다.
  • 방법은 아래와 같이 사용하시면 됩니다.
using Akka.Actor;
using System;

namespace interfaceTest
{
    class Program
    {
        // 액터 시스템 생성
        static ActorSystem system = ActorSystem.Create("actorSystem");

        static void Main(string[] args)
        {
            // Actor 생성
            IActorRef actor = system.ActorOf(ExampleActor.Props(), "actor");

            // SelectionActor 생성
            IActorRef selectionActor = system.ActorOf(SelectionActor.Props(), "selectionActor");

            system.WhenTerminated.Wait();
        }
    }

    public class ExampleActor : ReceiveActor
    {
        public static Props Props()
        {
            return Akka.Actor.Props.Create(() => new ExampleActor());
        }

        public ExampleActor()
        {
            // 자식 엑터 생성
            IActorRef childActor = Context.ActorOf(ChildActor.Props(), "childActor");

            //부모가 자식에게 메시지 보내기
            childActor.Tell("자식아, 부모다. 메시지 받아라.");

            // 메세지 받기
            Receive<string>(_ => Handle(_));
        }

        public void Handle(string message)
        {
            Console.WriteLine($"ExampleActor Re : {message}");
        }
    }

    public class ChildActor : ReceiveActor
    {
        public static Props Props()
        {
            return Akka.Actor.Props.Create(() => new ChildActor());
        }

        public ChildActor()
        {
            //부모에게 메시지 보내기
            Context.Parent.Tell("부모님, 자식된 도리로써 인사 드립니다.");

            // Selection으로 메시지 보내기
            Context.ActorSelection("akka://actorSystem/user/selectionActor").Tell("SelectionActor 는 메시지 잘 받아라.");

            Receive<string>(_ => Handle(_));
        }

        public void Handle(string message)
        {
            Console.WriteLine($"ChildActor Re : {message}");
        }
    }

    public class SelectionActor : ReceiveActor
    {
        public static Props Props()
        {
            return Akka.Actor.Props.Create(() => new SelectionActor());
        }

        public SelectionActor()
        {
            // 메세지 받기
            Receive<string>(_ => Handle(_));
        }

        public void Handle(string message)
        {
            Console.WriteLine($"SelectionActor Re : {message}");

            // 나한테 메시지 보낸 Actor에게 다시 메시지 보내기
            Sender.Tell("나한테 보낸 액터에게 다시 메시지 보내라");
        }
    }
}

실행 결과

ExampleActor Re : 부모님, 자식된 도리로써 인사 드립니다.
ChildActor Re : 자식아, 부모다. 메시지 받아라.
SelectionActor Re : SelectionActor 는 메시지 잘 받아라.
ChildActor Re : 나한테 보낸 액터에게 다시 메시지 보내라
728x90

이 글을 공유하기

댓글

Designed by JB FACTORY