54 CHEN

Java中使用akka手记二 Cluster

基础知识

依赖

maven中添加akka-cluster包:

1 2 3 4 5

<dependency>
              <groupId>com.typesafe.akka</groupId>
              <artifactId>akka-cluster_2.10</artifactId>
              <version>2.3.1</version>
          </dependency>

配置

下面的配置启用了Cluster。application.conf

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20

akka {
    actor {
      provider = "akka.cluster.ClusterActorRefProvider"
    }
    remote {
      log-remote-lifecycle-events = off
      netty.tcp {
        hostname = "127.0.0.1"
        port = 0
      }
    }
  
    cluster {
      seed-nodes = [
        "akka.tcp://ClusterSystem@127.0.0.1:2551",
        "akka.tcp://ClusterSystem@127.0.0.1:2552"]
  
      auto-down-unreachable-after = 10s
    }
  }

这里面定义的seed节点,用来作为cluster的初始化和加入点。要跨机器的话,就要修改这里的127.0.0.1了。

代码

下面是一个使用cluster的actor实现:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21

public class SimpleClusterListener extends UntypedActor {
    LoggingAdapter log = Logging.getLogger(getContext().system(), this);
    Cluster cluster = Cluster.get(getContext().system());
  
    //subscribe to cluster changes
    @Override
    public void preStart() {
      //#subscribe
      cluster.subscribe(getSelf(), ClusterEvent.initialStateAsEvents(), 
          MemberEvent.class, UnreachableMember.class);
      //#subscribe
    }
  
    //re-subscribe when restart
    @Override
    public void postStop() {
      cluster.unsubscribe(getSelf());
    }
  
    @Override
    public void onReceive(Object message) {

加入种子节点

自动和手动down机

cluster的事件

代码

原创文章如转载,请注明:转载自五四陈科学院[http://www.54chen.com]

Posted by 54chen java,akka

« java中使用akka手记一 java中使用akka手记三 cluster详例 »