Akka Hello World(Java 8)

將此依賴項新增到專案 POM:

<dependency>
        <groupId>com.typesafe.akka</groupId>
        <artifactId>akka-actor_2.11</artifactId>
        <version>2.4.4</version>
</dependency>

建立一個 Actor

public class HelloWorldActor extends AbstractActor {

    public HelloActor() {
        receive(ReceiveBuilder
            .match(SayHello.class, this::sayHello)
            .match(SayBye.class, this::sayBye)
            .build());
    }

    private void sayHello(final SayHello message) {
        System.out.println("Hello World");
    }

    private void sayHello(final SayBye message) {
        System.out.println("Bye World");
    }

    public static Props props() {
        return Props.create(HelloWorldActor.class);
    }
}

為 actor 建立一個 Junit 測試

public class HelloActorTest {

    private ActorSystem actorSystem;

    @org.junit.Before
    public void setUp() throws Exception {
        actorSystem = ActorSystem.create();
    }

    @After
    public void tearDown() throws Exception {
        JavaTestKit.shutdownActorSystem(actorSystem);
    }

    @Test
    public void testSayHello() throws Exception {
        new JavaTestKit(actorSystem) {
            {
                ActorRef helloActorRef = actorSystem.actorOf(HelloWorldActor.props());
                helloActorRef.tell(new SayHello(), ActorRef.noSender());
                helloActorRef.tell(new SayBye(), ActorRef.noSender());
            }
        };
     }
 }