Akka-Build a toolset for highly concurrent, distributed, and fast-recovering message-driven applications on the JVM
We believe that it is too difficult to write the correct concurrency program with fault tolerance and scalability. This is mostly because we use the wrong tool and the wrong level of abstraction. Akka was born to change the situation. By using the Actor model we raise the level of abstraction and provide a better platform (tool) for building the right extensible concurrency application.
What is the Actor model?
(Actor model) is a model on a concurrency operation. An "actor" is a procedural abstraction that is considered a basic unit of concurrent operations: When a participant receives a message, it can make some decisions, create more participants, send more messages, and decide how to answer the next message. The participant model was presented in 1973 in a paper by Carl Hewitt, Peter Bishop and Richard Steiger.
* The philosophy advocated by the participant model is "everything is a participant", which is similar to "Everything is Object" in object-oriented programming, but object-oriented programming is usually executed sequentially, and the actor model is executed in parallel.
* The sender is decoupled from the message that has been sent, and is the fundamental advantage of the participant model. This allows for asynchronous communication while satisfying the control structure of the messaging
* Message receivers are distinguished by address and are sometimes referred to as "e-mail addresses." So the participant can only communicate with the participant whose address it has. It can obtain an address from the received information, or get the address of the participant it created.
* The participant model is characterized by a parallel calculation within or between participants, where participants can be created dynamically, the participant address is contained in the message, and the interaction is communicated only through direct asynchronous messages, without limiting the order in which messages arrive.
Ok.. We summarize some, (in the case of a comparison of ground gas), in a system based on the actor model,
We use actors instead of the names of the objects, we can directly treat the TA as a person
The call between objects becomes the delivery of the message, and the process of message passing is asynchronous.
Each actor is born parallel, TA has been busy checking their mailbox, "marking a variety of memorial"
Between actors is to find each other's by address (mail)
Actor is also a human social decency has the same level of relationship
A unique hybrid model is implemented based on this model.
Actors
Simple, high-level abstraction of concurrent/parallel programs
Asynchronous, non-blocking, high-performance event-driven programming model
Very lightweight event-driven processing (1G memory can hold approximately 2.5 million actors)
Fault tolerance (Fault tolerance)
Using the "Let-it-crash" semantics and the supervisor tree structure to implement fault tolerance
Regulators tree structure can provide true high-fault-tolerant systems across multiple JVMs
Ideal for writing high-fault-tolerant systems that never stop, self-heal.
Path Transparency (location Transparency)
All elements of Akka are designed for distributed environments: All actors are interoperable by sending messages only, and all operations are asynchronous
Persistence (persistence)
Messages received by the actor can be optionally persisted and replayed (re-read) when the actor is started or restarted
All actors are interoperable by sending messages only, and all operations are asynchronous
This allows the actor to reset their state, when the JVM crash or the actor migrates to other nodes (node).
Actor in the Akka
An actor is a container that contains state, behavior, a mailbox, a child actor, and a regulatory policy. All of this is contained in an actor reference.
Actor Reference (citation)
Actors need to be isolated from the outside world to benefit from the actor model. So the actor is presented to the outside world in the form of an actor, and the actor reference can be transmitted freely and without restriction.
This partitioning of internal objects and external objects makes all desired operations transparent:
Restart actor without needing to update references elsewhere
Place the actual actor object on the remote host
Send messages to each other in different applications
Shielding Internal state
State (status)
The actor object usually contains variables to reflect the possible state of the actor. This may be a definite state machine (e.g. using an FSM module), or a counter, a set of listeners, pending requests, and so on. This data makes the actor valuable and must be protected from other actors. The good news for {color} is that each Akka actor has its own lightweight thread, which is completely isolated from the rest of the system. This means that you don't need to use locks for resource synchronization, so you can write your actor code without worrying about concurrency.
Behind the scenes, Akka runs a set of actors on a set of threads, usually many actors share a thread, and calls to one actor may be processed on different threads. Akka guarantees that this implementation detail does not affect the single-threaded handling of the actor state.
Because the internal state is critical to the actor's operation, state inconsistencies are fatal. When the actor fails and is restarted by its supervisor, the status is recreated as if the actor were created for the first time. This is to achieve the "self-healing" of the system.
Behavior (behavior)
Each time a message is processed, the message matches the actor's current behavior.
A behavior is a function that defines the action to be taken to process the current message, such as if the customer has already authorized it, then requests are processed, otherwise the request is rejected.
This behavior may change over time, for example, because different clients are authorized at different times, or because the actor enters the "non-service" mode and then returns. {color: #000000} The actor object usually contains variables to reflect the possible state of the actor. This may be a definite state machine (e.g. using an FSM module), or a counter, a set of listeners, pending requests, and so on. This data makes the actor valuable and must be protected from other actors. The good news is that conceptually each Akka actor has its own lightweight thread, which is completely isolated from the rest of the system. This means that you don't need to use locks for resource synchronization, so you can write your actor code without worrying about concurrency. {color}
Behavior matches, not message matching. A behavior is a function, a function that processes a particular message.
Another way of saying
We have defined 3 receive methods. Name Receive-a,receive-b,receive-c
Depending on the circumstances, cut different behavior. Supports hot switching. (This concept can refer to an FSM) behind the scenes, Akka will run a set of actors on a set of threads, usually many actors share a thread, and a call to an actor might be handled on a different thread. Akka guarantees that this implementation detail does not affect the single-threaded handling of the actor state.
Because the internal state is critical to the actor's operation, state inconsistencies are fatal. When the actor fails and is restarted by its supervisor, the status is recreated as if the actor were created for the first time. This is to achieve the "self-healing" of the system.
Mailbox (email)
The actor's purpose is to process messages that are sent from other actors (or from outside the actor system). The link between the sender and the receiver is the actor's mailbox: Each actor has and only one mailbox, and all the messages sent are queued in the mailbox. Queuing is performed in chronological order of the send operation, which means that messages sent from different actors do not have a fixed order at run time, because the actors are distributed in different threads. From another perspective, sending multiple messages from the same actor to the same actor, the messages are queued in the order they were sent.
You can have different mailbox implementations to choose from, the default is that the order in which messages are processed by Fifo:actor is consistent with the order in which messages are queued. This is usually a good choice, but the app may need to prioritize some messages. In this case, the priority mailbox can be used to place the message at a specified location based on the message priority, possibly even the queue header, rather than the end of the queue. If such a queue is used, the order in which messages are processed is determined by the algorithm of the queue, not the FIFO.
An important difference between Akka and other actor models is that the current behavior must handle the next message that is taken out of the queue, and Akka does not scan the mailbox to find the next matching message. The inability to process a message is usually handled as a failure condition unless the actor overrides the behavior.
Children (child actor)
Each actor is a potential regulator: if it creates a child actor to delegate the processing of subtasks, it automatically supervises them. The child actor list is maintained in the context of the actor, which the actor can access.
Changes to the child actor list are made by creating (Context.actorof (...)) Or Stop (context.stop (child)) sub-actors to implement, and these changes will take effect immediately. The actual creation and stop operations are done asynchronously behind the scenes so that they do not "block" their supervisors.
Supervisor strategy (Regulatory strategy)
The last part of the actor is the mechanism it uses to handle the error condition of its child actors. Error handling is handled transparently by Akka.
Since the strategy is the basis of the actor system's organizational structure, it cannot be modified once the actor has been created.
Consider that there is only one strategy for each actor, which means that if a actor's sub-actors apply a different strategy, the sub-actors should be grouped according to the same strategy, generating intermediate supervisors, and again tending to organize the actor system's structure according to the task-to-sub-task division.
actor System (viewed from a system perspective )
In a sense, actors are the most rigorous form of object-oriented, but at the end of the day they are seen as someone who , when used to model a solution, imagines the actor as a group of people, assigns tasks to them, and organizes their functions into a The structure of the organization , consider how to upload the failure step by step (fortunately we do not need to really deal with people, so that we do not need to care about their emotional state and moral issues). The result is a framework for software implementation in the brain.
Tree-shaped structure
Like an economic organization, actors naturally form a tree structure. The actor in charge of a function in a program may need to split its tasks into smaller, more manageable parts. For this it initiates the child actors and supervises them. That is, each actor has and has only one supervisor, the actor who created it.
The essence of the Actor system is that the task is split up and commissioned, until the task is small and can be processed in its entirety. This not only allows the task itself to be clearly divided into structures, but the final actor can be parsed according to the type of message they "should handle", "How to complete the normal process" and "how the failure process should be handled." If an actor is unable to process a situation, it sends a corresponding failure message to its regulator to ask for help. Such a recursive structure allows failures to be handled at the right level.
This can be compared to a layered design approach. Layered design methods can ultimately easily form defensive programming to prevent any failure from being compromised. Putting the problem in the right hands is a better solution than "hiding" everything.
Supervision
Regulation describes the relationship between actors: Supervisors delegate tasks to subordinates and respond to failures of subordinates. When a subordinate fails (i.e. throws an exception), it suspends itself and all of its subordinates and sends a message to its supervisor that fails. Depending on the nature of the work being supervised and the nature of the failure, regulators can have 4 basic options
Let subordinates continue to execute, keep subordinate, clear subordinate's internal state is the current internal state
Restart subordinates to clear the internal status of subordinates
Permanently terminate subordinates
Passing failures up the regulatory tree
It is important to always think of an actor as part of the entire regulatory tree, which explains the meaning of the 4th option (since a regulator is also a subordinate of the regulator above it) and is implied in the first 3 choices:
Let the actor continue execution and will continue to execute its subordinates,
Restarting an actor must also restart its subordinates,
Terminating an actor in a similar way terminates all of its subordinates.
Let the actor continue execution while continuing to execute its subordinates, restarting an actor and having to restart its subordinates, terminating an actor in a similar way terminates all of its
Actor is suspended, calling the Supervisionstrategy.handlesupervisorfailing method of the old instance (the default implementation is to suspend all child actors)
Call the Prerestart hook of the old instance (the default implementation is to send a termination request to all child actors and call Poststop)
Wait for all child actors to terminate until Prerestart finally ends
Call the Supervisionstrategy.handlesupervisorrestarted method of the old instance (the default implementation is to send a restart request to all remaining child actors)
Re-invoke the previously provided actor factory to create a new actor instance
Call Postrestart recovery on a new instance to run the new actor
Before the actor path, one more actor reference
The origin and function of actor references are mentioned earlier. This is a further introduction to the actual content. The actor reference is a subclass of Actorref, and its most important function is to support sending messages to the actor it represents. Each actor accesses its standard (local) reference through self, and the reference is included by default in messages sent to other actors. In turn, during message processing, the actor can access a reference to the sender of the current message through sender.
Supports several different actor references, depending on the configuration of the actor system
Pure local references are used in an actor system that is configured to not use network functionality. These actor references cannot be transmitted outward from the network connection in a condition that maintains its functionality.
Local references that support remote invocation are used in an actor system that supports network functionality between actor references in the same JVM. In order to be recognized after being sent to other network nodes, these references contain protocol and remote address information
The local actor reference has a subclass that is used in routing (routers, i.e. Mixin Router trait actor). Its logical structure is the same as the previous local reference, but the message sent to them is redirected directly to its child actor.
The remote actor reference represents a actor,i.e that can be accessed through remote communication. When a message is sent to them from another JVM, Akka transparently serializes the message
PS: There is no difference in the use of the process. Because they are all actorref subclasses, and we are using this top class abstract.
Actor Path
Since the actor is created in a strict tree structure style, there is a unique actor name sequence along the chain of custody of the child actor to the parent actor to the root of the actor system. This sequence can be likened to a file path in the filesystem, so we call it "path". Just like in some real file systems, there are so-called "symbolic links", i.e. an actor may be accessed through a different path, except for the original path, and the other path contains the conversion method of the actor's actual supervisory ancestor chain. These features are described in the following sections.
An actor path consists of an anchor point that identifies the actor system, followed by each path element connected, from the root to the specified actor, and the path element is the name of the actor whose path is passed, separated by "/".
Each actor path has an address component that describes how to access the actor's protocol and location, followed by the actor's name on the tree node from the root to the actor. For example:
"Akka://my-sys/user/service-a/worker1"//Purely local "akka.tcp://[email protected]:5678/user/service-b" Remote
Logical actor Path: The only path that follows the actor's parent chain of custody to the root is called the logical actor path. This path is exactly the same as the actor's creator ancestor, so when the actor system's remote invocation configuration (and the address portion of the path in the configuration) is set, it is fully deterministic.
Physical path: The logical actor path describes the functional location within an actor system, while a configuration-based remote deployment means that one actor may be created on another network host, i.e. in another actor system. In this case, it is an expensive operation to access the network from the root through the actor path. Therefore, each actor also has a physical path, starting at the root of the actor system where the actual actor is located. The use of physical paths as sender references when communicating with other actors allows the receiver to reply directly to the actor, minimizing the routing delay.
* An important aspect is that physical paths never span multiple actor systems or across virtual machines. This means that the logical path of an actor (the regulatory tree) and the physical path (actor deployment) may be forked if its ancestors were remotely supervised
"/USER" is the supervisor of all top actors created by the user, the actor created with Actorsystem.actorof at its next level "/system" Is the supervisor of all top-level actors created by the system (such as log listeners or actors that are configured to automatically deploy when the actor system starts) "/deadletters" is the Badmail actor, and all messages destined for the terminated or nonexistent actor will be sent here "/ Temp "is the watchdog of all system-created short-time actors (i.e. actors used in Actorref.ask implementations)." /remote "is a man-made path used to store all actors whose regulators are remote actor references
Let's get a picture.
650) this.width=650; "src=" Http://s5.51cto.com/wyfs02/M02/7D/57/wKioL1bmeLeBbnSgAACz5TUZdOY737.png "title=" Actorpath.png "width=" height= "border=" 0 "hspace=" 0 "vspace=" 0 "style=" width:400px;height:200px; "alt=" Wkiol1bmelebbnsgaacz5tuzdoy737.png "/>
Can draw a few conclusions from
The root path of the application level is "/user". All the actors that were created were under him.
An actor has a father actor and a child actor. The path shows his position in the tree structure.
Find an actor that can be found directly from the path, or through Actorref's parent-child search.
The last point above is more evident in the code.
Context.actorselection (".. /broder ")! msg//Find Context.actorselection by relative path ("/user/servicea")! msg//through absolute path context.actorselection (".. /*") ! MSG//Support UNIX Shel path wildcard character
This article is from the "Half Bowl porridge" blog, please be sure to keep this source http://sioux.blog.51cto.com/1146975/1750898
Actor First Knowledge