akka入門-簡單示例

liuchangqing123發表於2015-05-17
以下程式演示了akka的一個簡單的示例。建立Actor去處理一條命令,通過訊息傳遞的方式進行互動。


我使用的akka版本和相關jar包參見pom檔案:

<project xmlns= "http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation= "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion >4.0.0 </modelVersion>

  <groupId >com.focusedu.akka </groupId>
  <artifactId >akka-first</ artifactId>
  <version >0.0.1-SNAPSHOT </version>
  <packaging >jar </packaging>

  <name >akka-first</ name>
  <url >http://maven.apache.org </url>

  <properties >
    <project.build.sourceEncoding> UTF-8</ project.build.sourceEncoding>
  </properties >

  <dependencies >
    <dependency >
      <groupId >junit</groupId>
      <artifactId >junit</artifactId>
      <version >3.8.1 </version>
      <scope >test </scope>
    </dependency >
    <dependency >
         <groupId> com.typesafe.akka</groupId >
         <artifactId> akka-actor_2.10 </artifactId>
         <version> 2.3.10</ version>
     </dependency >
     <dependency >
           <groupId> log4j</ groupId>
           <artifactId> log4j</ artifactId>
           <version> 1.2.17</ version>
     </dependency >
     <dependency >
           <groupId> com.google.guava</groupId >
           <artifactId> guava</artifactId >
           <version> 18.0</ version>
     </dependency >
     <dependency >
        <groupId> ch.qos.logback</groupId >
        <artifactId> logback-classic </artifactId>
        <version> 1.1.1</ version>
    </dependency >
    <dependency >
        <groupId> com.typesafe.akka</groupId >
        <artifactId> akka-persistence-experimental_2.10 </artifactId>
        <version> 2.3.10</ version>
    </dependency >
     
  </dependencies >
</project>
 

1.建立事件Event

import java.io.Serializable;

public class Event implements Serializable {

  private String data;
  private String uuid;


  public Event(String data) {
    super();
    this. data = data;
  }

  public Event(String data, String uuid) {
    this. data = data;
    this. uuid = uuid;
  }

  public String getData() {
    return data;
  }

  public String getUuid() {
    return uuid;
  }

  @Override
  public String toString() {
    return "Event{" + "data='" + data + '\'' + ", uuid='" + uuid + '\'' + '}' ;
  }
}

2.建立命令物件
其中主要的方法是重寫onReceive方法,用於處理接收到的訊息。

import java.io.Serializable;

public class Command implements Serializable {
     private static final long serialVersionUID = 1L;
     private final String data ;

     public Command(String data) {
           this.data = data ;
     }

     public String getData() {
           return this .data ;
     }

     @Override
     public String toString() {
           return "Command{" + "data='" + data + '\'' + '}';
     }
}
3.建立Actor物件

import java.util.UUID;

import com.center.akka.simple.command.Command;
import com.center.akka.simple.event.Event;

import akka.actor.UntypedActor;
import akka.event.Logging;
import akka.event.LoggingAdapter;

public class SimpleActor extends UntypedActor {

     LoggingAdapter log = Logging.getLogger(getContext().system(), this);

     public SimpleActor() {
           log.info( "SimpleActor constructor");
     }

     @Override
     public void onReceive(Object msg) throws Exception {

           log.info( "Received Command: " + msg );
           if (msg instanceof Command) {
               final String data = ((Command) msg).getData();
               final Event event = new Event(data, UUID.randomUUID().toString());
               // emmit an event somewhere...

          } else if (msg .equals("echo" )) {
               log.info( "ECHO!");
          }
     }
}

4.測試類

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.actor.Props;

import com.center.akka.simple.actor.SimpleActor;
import com.center.akka.simple.command.Command;

/**
 *
 * @author lcq
 *
 */
public class System {

  public static final Logger log = LoggerFactory.getLogger(System.class);

  public static void main(String... args) throws Exception {

    final ActorSystem actorSystem = ActorSystem.create("actor-system");

    Thread.sleep(5000);

    final ActorRef actorRef = actorSystem.actorOf(Props.create(SimpleActor. class), "simple-actor");

    actorRef.tell( new Command("CMD 1" ), null);
    actorRef.tell( new Command("CMD 2" ), null);
    actorRef.tell( new Command("CMD 3" ), null);
    actorRef.tell( new Command("CMD 4" ), null);
    actorRef.tell( new Command("CMD 5" ), null);

    Thread.sleep(5000);

    log.debug( "Actor System Shutdown Starting..." );

    actorSystem.shutdown();
  }
}

需要區分的兩個概念是:
actorRef.tell:非同步傳送一個訊息並立即返回; 
actorRef.ask:非同步傳送一條訊息並返回一個 Future代表一個可能的迴應; 
所以總是使用tell更偏向效能,除非必須才用ask


執行結果:

[INFO] [05/17/2015 17:46:44.224] [actor-system-akka.actor.default-dispatcher-3] [akka://actor-system/user/simple-actor] SimpleActor constructor
[INFO] [05/17/2015 17:46:44.225] [actor-system-akka.actor.default-dispatcher-3] [akka://actor-system/user/simple-actor] Received Command: Command{data='CMD 1'}
[INFO] [05/17/2015 17:46:44.312] [actor-system-akka.actor.default-dispatcher-3] [akka://actor-system/user/simple-actor] Received Command: Command{data='CMD 2'}
[INFO] [05/17/2015 17:46:44.312] [actor-system-akka.actor.default-dispatcher-3] [akka://actor-system/user/simple-actor] Received Command: Command{data='CMD 3'}
[INFO] [05/17/2015 17:46:44.312] [actor-system-akka.actor.default-dispatcher-3] [akka://actor-system/user/simple-actor] Received Command: Command{data='CMD 4'}
[INFO] [05/17/2015 17:46:44.312] [actor-system-akka.actor.default-dispatcher-3] [akka://actor-system/user/simple-actor] Received Command: Command{data='CMD 5'}
17:46:49.226 [main] DEBUG com.center.akka.simple.app.System - Actor System Shutdown Starting...