初识Akka之Router

来源:互联网 发布:java音乐网站系统 编辑:程序博客网 时间:2024/06/06 00:06

背景介绍


        简单来说Akka是一个用于构建服务端分布式应用的框架,其具有高并发、可扩展、容错性等特点。Akka中的基本单位是Actor,Actor可以与线程来作为类比,有自己的标识符、存储空间、调度策略、生命周期等。每个Actor相互之间的交互都是通过消息(可以是字符串、二进制数据、自定义对象等)来实现的,这样就避免了每个Actor的耦合。更重要的是生成一个Actor只占用40多个字节的存储空间(我自己测试的是50字节左右),1G内存的情况下,可以生成250w个Actor!其并发性能超强悍~~~

     Akka官方文档:http://akka.io/docs/

      背景知识简要介绍完了,本篇的主题是怎样实现Akka文档中介绍的router

      router即路由,消息传递到router后,router根据响应的策略将消息下发到其所管理的routees, routees可以看做是一系列Actor的集合,每个Actor当然既可以是本地的Actor也    可以是远程的Actor。本文将给出本地和远程的两种测试实例。

准备工作:

   开发环境:ItelliJ IDEA

   工程类型:Maven

1.工程目录结构




2.Maven 配置文件

<?xml version="1.0" encoding="UTF-8"?><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.akka.route</groupId>    <artifactId>akka</artifactId>    <version>1.0-SNAPSHOT</version>    <name>${project.artifactId}-${project.version}</name>    <repositories>        <repository>            <id>akka-snapshots</id>            <name>Akka Snapshots</name>            <url>http://repo.akka.io/snapshots/</url>            <layout>default</layout>        </repository>    </repositories>    <dependencies>        <dependency>            <groupId>com.typesafe.akka</groupId>            <artifactId>akka-actor_2.11</artifactId>            <!--Must be 2.2-SNAPSHOT-->            <version>2.3.12</version>        </dependency>        <dependency>            <groupId>com.typesafe.akka</groupId>            <artifactId>akka-remote_2.11</artifactId>            <version>2.3.12</version>        </dependency>        <dependency>            <groupId>org.apache.maven.archetypes</groupId>            <artifactId>maven-archetype-quickstart</artifactId>            <version>1.1</version>        </dependency>    </dependencies></project>


此项目中用到的akka版本是2.3.12,对应的远程模块remote版本也是2.3.12


3.akka配置文件 application.conf

# akka 2.3LocalSys{  akka {    actor {      provider = "akka.remote.RemoteActorRefProvider"      deployment {        /router1{          router = round-robin-pool          nr-of-instances = 5        }        /router3{          router = random-group          routees.paths = [            #set the remote actor path            "akka.tcp://RemoteNodeApp@192.168.86.129:2552/user/remoteActor",            #set the localhost actor path            "akka.tcp://RemoteNodeApp@127.0.0.1:2552/user/remoteActor"          ]        }      }    }  }}


Akka的配置文件很复杂,此处只给出了需要的配置。


3.Main 程序

import akka.actor.*;import akka.event.Logging;import akka.event.LoggingAdapter;import com.typesafe.config.ConfigFactory;/** * Created by rootigo on 2016/7/28. */public class Main {   /**For a remote akka project ,the top system must be set once,otherwise it will cause "Address already in use" exception,   *The akka use default port 2552   */    public static ActorSystem _system = ActorSystem.create("parent", ConfigFactory            .load().getConfig("LocalSys"));    public static void main(String[] args) throws InterruptedException {       ActorRef masterRef =               _system.actorOf(Props.create(Master.class),"Master");       for(int i = 0 ;i < 10;i ++) {           int payload = i * 10;           masterRef.tell(new Work(""+payload+""), null);           Thread.sleep(1000 * 2);       }   }}


Main是此项目的启动程序,先根据配置文件application.conf创建ActorSystem,后面由此system创建的Actor都在此system根路径之下,即/parent/user/some_actor


4.Work文件

import java.io.Serializable;import java.util.Arrays;import java.util.List;import akka.actor.*;import akka.event.Logging;import akka.event.LoggingAdapter;import akka.routing.*;import com.typesafe.config.ConfigFactory;public final class Work implements Serializable{    private static final long serialVersionUID = 1L;    public String payload;    public Work(String payload){        this.payload = payload;    }}     /** Route Logic       * RoundRobinRoutingLogic       * RandomRoutingLogic       * SmallestMailboxRoutingLogic       * BroadcastRoutingLogic       * ScatterGatherFirstCompletedRoutingLogic       * TailChoppingRoutingLogic       * ConsistentHashRoutingLogic       * */class Master extends UntypedActor {    LoggingAdapter log = Logging.getLogger(getContext().system(), this);    ActorRef getRouteeRef(){              ActorRef workerpool = Main._system.actorOf(Props.create(Worker.class)        );        return workerpool;    }    ActorRef getRemoteRouter(String remoteAddr){              String remoteActorAddr = String.format("akka.tcp://RemoteNodeApp@%s/user/remoteActor",remoteAddr);        ActorRef routerRemote = getContext().actorFor(remoteActorAddr);        return routerRemote;    }    ActorRef getRoundRobinPoolRef(){        //Props.create(Worker.class) means create a Worker actor        ActorRef routerRef = Main._system.actorOf(FromConfig.getInstance().props(Props.create(Worker.class)),"router1");        System.out.printf("RoundRobinGroup actor path is:{%s}\n",routerRef.path());        return routerRef;    }    ActorRef getRoundRobinGroupRefByCoding(){        //Before using RoundRobinGroup(paths) to router w1,w2,w3,this three actors must be created        Main._system.actorOf(Props.create(Worker.class),"w1");        Main._system.actorOf(Props.create(Worker.class),"w2");        Main._system.actorOf(Props.create(Worker.class),"w3");        ///Round-robin-Group by program code        List<String> paths = Arrays.asList("/user/w1", "/user/w2",                "/user/w3");        ActorRef routerRef = Main._system.actorOf(new RoundRobinGroup(paths).props(), "router2");        ActorRef w1 = Main._system.actorFor("/user/w1");        ActorRef w2 = Main._system.actorFor("/user/w2");        ActorRef w3 = Main._system.actorFor("/user/w3");        System.out.printf("W1 path:{%s,%s},W2 path:{%s,%s},W3 path:{%s,%s}\n",                w1.path(),w1.isTerminated(),w2.path(),w2.isTerminated(),w3.path(),w3.isTerminated());         /// Round-robin-group         System.out.printf("RoundRobinGroup actor path is:{%s}\n",routerRef.path());         return routerRef;    }    ActorRef getRoundRobinGroupRefByConfigureFile(){        //router the remote actor as routees,make sure that the remote actors must be running        ActorRef routerRef = Main._system.actorOf(FromConfig.getInstance().props(),"router3");        System.out.printf("RoundRobinGroup actor path is:{%s}\n",routerRef.path());        return routerRef;    }    void addRouteeProgramtically(List<Routee> routees){        for(int i = 0 ;i < 5;i++){            // ActorRef r = getContext().actorOf(Props.create(Worker.class),"Worker" + i);            String remoteAddr = "192.168.86.129:2552";            if(i % 2 ==0){                remoteAddr = "127.0.0.1:2552";            }            ActorRef r = getRemoteRouter(remoteAddr);            System.out.printf("{%s} path is {%s}\n",i,r.path());            getContext().watch(r);            routees.add(new ActorRefRoutee(r));        }    }    //1.Use router and routees to router the message    Router router ;    /*    {        List<Routee> routees = new ArrayList<Routee>();        ActorRef r = getRoundRobinGroupRefByConfigureFile();        getContext().watch(r);        routees.add(new ActorRefRoutee(r));        router = new Router(new RoundRobinRoutingLogic(),routees);    }    */    //2.Use the RoundRobinGroup or RoundRobinPool to get the router    ActorPath routerPath =  getRoundRobinGroupRefByConfigureFile().path();    public void onReceive(Object msg){        ActorRef sender = getSender();        if(msg instanceof String){            log.info("Msg From Sender[{}]:{}\n",sender.path(),msg);        }        else if(msg instanceof Work){            log.info("[{}]Send Forward Message:'{}' to router \n" ,getSelf().path(), ((Work) msg).payload,routerPath);            /*            //Sending messages via the router,the sender is the router iteself            router.route(((Work) msg).payload,getSelf());            */            ActorSelection selection = getContext().actorSelection(routerPath);            selection.tell(((Work) msg).payload,getSelf());        } else if(msg instanceof Terminated){            router = router.removeRoutee(((Terminated)msg).actor());            ActorRef r = getContext().actorOf(Props.create(Worker.class));            getContext().watch(r);            router = router.addRoutee(new ActorRefRoutee(r));        }    }}

需要强调的是,在用RoundRobinGroup(和其他Group)获取作为router的Actor时,一定要保证routees.path中涉及的远程Actor已经存在,否则消息无法正确传递。

方法getRoundRobinGroupByCoding()中的/user/w1,/user/w2,/user/w3三个Actor要提前创建。

从代码中可以看出,创建Router有两种方法,一种是通过向Router中逐个添加routee,另外一种就是用RoundRobinGroup或者RoudRobinPool来创建Router的ActorRef。


5.Worker文件

import akka.actor.ActorPath;import akka.actor.UntypedActor;import akka.event.Logging;import akka.event.LoggingAdapter;public class Worker extends UntypedActor {    LoggingAdapter log = Logging.getLogger(getContext().system(), this);    @Override    public void onReceive(Object msg){        ActorPath path = getSender().path();        ActorPath myself = getSelf().path();        if(msg instanceof  Work){            String payload = ((Work)msg).payload;            log.info("Receive Work({}) From :{}",payload,path);        } else if(msg instanceof  String){            log.info("Receive message:{} From :{}",msg,path);        }    }}



最后,还需要一个远程的服务端RemoteNodeApp,不再列出,下面给出附件,自行下载。

http://download.csdn.net/detail/igoqhb/9590561




0 0