Actor model and Akka

Source: Internet
Author: User
Actor model and Akka I. Actor model Actor Model ConceptA conceptual model for dealing with concurrency computation the state of an actor is maintained by its own behavior, and external threads cannot invoke the behavior of the object directly, and must pass the message to excite the behavior, thus guaranteeing that the actor's internal data is modified only by itself Actor Model Composition

The Actor model is detailed in the Actor model, everything can be abstracted as actor, an actor refers to a most basic computational unit, it can receive a message and based on the message to perform the calculation of the actor package state and behavior of the object, Their only way of communication is to exchange messages, analogy object: An object receives a message (method call), and then works according to the received message (which method is called) actor important feature is that the actors is isolated from each other, they do not share memory with each other, Craved is also different from the object above, that is, an actor can maintain a private state, and this state can not be changed by another actor actor exchange messages placed in the recipient's mailbox (Inbox), that the actor does not communicate directly between the actors, Instead, they communicate with each other by message, and each actor encapsulates everything it needs to do in its interior.
Each actor can have a status or be stateless when an actor receives a message, it can do one of the following three things: Create another actors, send a message to another actors, specify the behavior of the next message: that is actors how to modify the state Each actor has its own lightweight threads that protect them from other parts of the system, so when we write actors, we don't have to worry about concurrency through actors to simplify locks and thread management:
Provides an advanced abstraction that encapsulates state and operation, simplifies development application development provides an asynchronous, non-blocking/high-performance event-driven model super lightweight threading event-handling capability actor System

The life cycle of the actor
Actorref
It is a reference to the actor that sends a message to the actor it represents, and the actor can use the self () or sender () method to obtain the actor's reference to itself or the sender of the message, and in the actor system, the actor never communicates directly between the actors, The communication actor path must be established through their proxy actorref

Father and son actor
Tree structure, hierarchical management, and the atomization of complex transactions by recursion

The actor Path:actor system uniquely identifies the local actor
"Akka://my-sys/user/service-a/worker1" remote actor
"Akka.tcp://my-sys@host.example.com:2552/user/service-b" cluster actor
"Cluster://my-cluster/service-c"

The default node for actor path Root Guardian is the parent of all actors Actor/useractor is the father of all user-created actors Actor/user Systemactor is the parent actor of all system-created actors/ System Peer actor/*

two. Akka Akka is a Scala-compatible Scala and Java-compliant Actor model framework for high availability and scalability based on event-driven concurrency processing mode with high performance and high availability Simplifying the process of developing concurrent processing in application system Akka development process Define message model create actor
Implement business logic get actor
Need to use Akka to get to Actorsystem, and then according to the traffic of the business, get the appropriate actor, send Message message processing to the actor
In the implementation of the actor, the received message is processed or forwarded in order to create a business logic flow creating actor

Typedactor Active Object Design mode application: When invoking this instance of the method, asynchronous execution instead of synchronous execution Typedactor does not use the message, more is used to bridge the actor system and non-actor

Untypedactor is more like the invocation of a JMS calling method in Java and executes a fully dependent message, distinguishing between different executions by the type or content of the message.

In Akka we tend to use Untypedactor to deliver messages between actor systems Untypedactor

    public class Greetprinter extends untypedactor{

        @override public
        void OnReceive (Object message) throws exception{
            if (message instanceof greeting)
            System.out.println (((greeting) message). message);
        }
    }
Get actor

Three ways: actorof
Creates a new actor that creates an actor that is the immediate child actor of the context under which the method was called
The method returns a Actorref that represents the actor's reference, including a UID and a path. These two values collectively identify the uniqueness of an actor, and the Actorref life cycle ends when the actor stops actorselection
When a message is delivered, only the existing actor is found, and no new actor is created, and the target actors is not verified to exist
The method value is concerned with path and does not care about which actor, if you want to get a specific actor through actoselection, you need to call Actorselection's Resolveone method to get Actorfor
Only the existing actor will be found, not the new actor Akka other components

Dispatcher Distribution Device

When the number of actors is more, the communication between each other needs to be coordinated, so as to better balance the performance of the entire system execution
Feature: constant coordination on a separate thread, assigning messages from each actor to the execution thread
Four different Dispatcher Dispatcher: can be shared by multiple actors and implemented by ThreadPool

    Private list<actorref> createactors (int actorcount) { 
    Props Props = props.create (Writeractor.class). Withdispatcher ("Writer-dispatcher");
    list<actorref> actors = new arraylist<> (actorcount);
    for (int i=0;i<actorcount;i++) {
    actors.add (GetContext (). Actorof (Props, "Writer_" +i));
    }
    return actors;
    }
Pinneddispatcher Balancingdispatcher Callingthreaddispatcher Router Router

When there are multiple targets, Akka through the router mechanism, to effectively assign messages to the actor to complete the work, the actor router managed is called Routee

Use of router: can be used in the actor by instantiating the router object in the way you can also create a routeractor outside the actor by Withrouter way directly to use

Router Router = new Router (new Roundrobinroutinglogic ());

for (Actorref actor:actors) {
router = router.addroutee (actor);
}
Router.route ("Insert", Actorref.nosender ());
Router Routing policy
◦roundrobinpool: Polling for distributing messages
◦randompool: Distributing messages in random ways
◦balancingpool: Distribute Messages evenly
◦smallestmailboxpool: Minimum message mailbox distribution
◦broadcastpool: Broadcast Messages
◦scattergatherfirstcompletedpool: All child routee sent, first message reply
◦tailchoppingpool: Random delay send, first reply message
◦consistenthashingpool: Consistent hash of the way to distribute messages Scheduler Scheduler Akka Demo

Https://github.com/sunxiang0918/AkkaDemo three. Akka distributed messaging and applications in spark Akka remote invocation

The use of end-to-end (Peer-to-peer, peer-to) communication style design, simple and transparent: In addition to the message to be serialized and create and find the actor when the path is slightly different, there is no other difference, Akka not specifically for remoting to provide a specialized API, The difference is the configuration
Minimum configuration:

    akka{
        actor{
            Provider = "Akka.remote.RemoteActorRefProvider"
        }
        remote{
            enabled-transports = [" Akka.remote.netty.tcp "]
            netty.tcp{
            hostname =" 127.0.0.1 "
            port = 2552
            }
   }
Remote actor Create and get remote actor

Remote path:
Akka.tcp://wcmapreduceapp@127.0.0.1:2552/user/remoteactor
How to create:

    Actorsystem system = actorsystem.create ("Wcmapreduceapp",
    configfactory.load ("Application")
    . GetConfig ( "Wcmapreduceapp"));
    Aggregateactor = System.actorof (Props.create (Aggregateactor.class));

How to obtain:

    Final Actorref remoteactor = system.actorfor ("Akka.tcp://wcmapreduceapp@127.0.0.1:2552/user/remoteactor")
Remote actor RoutingLoad balancing and high availability
Akka remote invocation is based on the point-to-point model, does not support load balancing functions, but can be used through the actor routing mechanism to achieve load balancing and high availability
Ex: When a message is sent to/parent/remotepool, it is polled to distribute the message to different remote services
    akka.actor.deployment {
        /parent/remotepool{
        router = round-robin-pool
        nr-of-instances = ten
        Target.nodes = ["akka.tcp://app@10.0.0.2:2552", "akka://app@10.0.0.3:2552"]
        }
    }
Akka ClusterCluster call
Gossip protocol
Inverse entropy (anti-entropy): In a bounded network, each node randomly communicates with other nodes, and after a chaotic communication, the state of all nodes is eventually agreed
, with de-centering, full peering between nodes, no need for any central node, ultimate consistency Features
Gossip algorithm Example
Cassandra Redis

Akka cluster is based on the gossip Protocol, support service automatic failure detection, can automatically detect problems and leave the cluster member nodes, through the event-driven way, the state propagates to the other members of the entire cluster, a Akka cluster is composed of a group of member nodes, Each member node is uniquely identified by Hostname:port:uid, and each member node is completely decoupled

Node state

Cluster leader

Cluster configuration

The Akka in Spark
Using Akka as the RPC framework in distributed systems, many components are encapsulated as actors, control and state communication, and client,master and workers in spark are between a actor,actor and the message is sent through "!" Symbol send message, receive end to receive and process messages through case pattern matching in receiving method

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.