Distribution and routing of Akka

Source: Internet
Author: User
Tags join min throwable
a Dispatchers 1.1 Understanding the dispenser

The dispatcher is the role of a communications coordinator, primarily responsible for the receipt and delivery of messages. It is primarily based on a certain distribution strategy that controls the execution process and then routes incoming messages or requests to the relevant business processes.


Airlines that provide aircraft are similar to Akka's mailbox, and the airport runway resembles Akka's thread resources, and the air traffic control tower resembles dispatcher

1.2 Types of distributors 1.2.1 Dispatcher

This is the default dispatcher, which is an event-based, binding set of actors into a thread pool.

Features are as follows:

# each actor relies on their own mailbox

# can be shared by any number of actors

# is a non-blocking optimization

1.2.2 Pinneddispatcher

It provides a separate or dedicated thread for each actor, doing some I/O operations, or a task that performs some long-time computational tasks.

# each actor relies on their own mailbox

# for each actor, a dedicated thread cannot be shared with other actors

# The dispatcher relies on the execcutor of the thread pool

# is optimized for blocking operations 1.2.3 Balancingdispatcher

He can reassign work from the more busy actor to the more idle actor, the reallocation of tasks is premised on the premise that all actors must be of the same type.

Characteristics:

# only one mailbox

# The dispatcher is shared by all actors of the same type

# The dispatcher relies on a thread pool or fork join pool

1.2.4 Callingthreaddispatcher

He just runs the task on the same thread, can't create any new threads, and provides a sequence of executions

Characteristics:

# Each actor relies on his own mailbox

# All actors Shared Distributors

# The dispatcher relies on the current calling thread

use of 1.3 dispatcher

Executor Context supported by Akka:

First type: Thread poolexecutor

The worker thread pool is created and the task queue is assigned to the pool, and if the number of tasks exceeds the number of threads, then the queue waits until the pool has idle threads

The second type: Fork joinexecutor

This is based on the premise of sub-governance, his core idea is to divide a large task into a number of small tasks, and finally in the joint results, these tasks are able to run independently

For each executorcontext, Akka can specify a profile parameter, which is defined primarily:

# Number of threads allocated for the minimum number of

# Maximum number of threads allocated

# The coefficients used (based on the number of CPU cores available)

For example, the minimum number of threads is 3 and the coefficient is 2, then dispatcher can start 6 threads altogether.

1.4 How to configure Parameters

It will default to read the application.conf file under Classpath, so you can define a file and configure it inside

Akka {  loglevel = INFO} # Your dispatcher name My-dispatcher {  # Specify dispatcher type [Dispatcher/pinneddispatcher/bala Ncingdispatcher/callingthreaddispatcher]   type = Dispatcher   # Specifies which kind of Executor Context to use [
Thread-pool-executor/fork-join-executor]   executor = "Fork-join-executor"   # Configuration parameters for executor context type   Fork-join-executor {    # minimum concurrency     parallelism-min = 2     # concurrency Factor can Total concurrency Count ceil (available processors * factor)     Parallelism-factor = 2.0     # max concurrency      Parallelism-max = ten  }   thread-pool-executor {    # thread pool minimum threads     Core-pool-size-min = 2     # factor (effective number of cores) * factor     Core-pool-size-factor = 2.0   &nbsp ; # thread pool Max threads     Core-pool-size-max = ten  }   # The throughput of the maximum message that each actor can handle before jumping to another actor   # is set to 1, for Every actor is fair.   Throughput = +   # Specify MAIlbox capacity Size, if set to 0 means no bounds   mailbox-capacity =   # Specifies the type of mailbox, this should mate Mailbox-capacity   # Mailbox-type = ""
}

1.5 What kind of dispatcher strategy to choose

# The choice of the dispatcher depends on whether your application is blocking or non-blocking

# The choice of executor depends on your application logic, whether you need to divide a task into smaller tasks, and then each small task can run in parallel

# Determine the maximum and minimum number of threads based on the number of CPU cores

# Throughput Settings

A simple example:

Class Dispatcheractor extends untypedactor{    val x:int = 2     var child:actorref = _ &nb sp;   @throws [Exception] (classof[exception]) override     def prestart (): Unit = {         child = Context.actorof (props[msgechoactor],name= "Msgechoactor")     }     @throws [Throwable] (classof[throwable])     override def onreceive (message: Any): Unit = {        println ("[onreceive] =" +message)          var result = 0         try {             result = x + message.toString.toInt          Catch {            case t:throwable = T.printstacktrace ()        }         Child.tell (Result,sender)    }} class Msgechoactor extends Actor { &nbs p;  def receive:receive = {        case a if 1 to ten contains (a) =  &nbs p;          println (S "$a belongs to [1-10]")          Case B if one to contains (b) =           & nbsp println (S "$b belongs to [11-50]")         Case C if Wuyi to contains (c) =  & nbsp;          println (S "$c belongs to [51-100]")          Case _ =             println (" Unknown Range Value ")    }} object Dispatcheractor extends App {    val _system = actorsy Stem ("Dispatcheractorsystem")    Val dispatcheractor = _system.actorof (Props[dispatcheractor]        . Withdispatcher ("My-dispatcher"), name= "Dispatcheractor")     Dispatcheractor!     Dispatcheractor!     Dispatcheractor! 1     thread.sleep (+)     _system.terminate ()}

two MailBox

Mailboxes, where messages are stored temporarily, and then these messages are sent to the actor, and in general, each actor relies on a mailbox, but Balancingpool allows all actors to share a mailbox

2.1Mailbox Type

The following are some of the default mailbox implementations

They rely on the queues in Java's concurrent libraries:

Blocking queue: Blocking queues means that if a queue is full, the queue will block until there is empty space to hold the data

Bounded queue: Boundary queues mean that the queue has a size limit and cannot continue to store data if the specified number is reached

Unbounded MailBox: If the Akka.actor.default-mailbox configuration is not modified, it is the default MailBox type.

Configuration name: unbounded or Akka.dispatch.UnboundedMainbox

Singleconsumeronlyunboundedmailbox:

Relies on multiple producers and individual consumer queues, cannot be used by Balancingdispatcher, is not blocking queues, and has no boundaries

Configuration name: akka.dispatch.SingleConsumerOnlyUnbounded

Unboundedcontrolawaremailbox: Non-blocking, borderless, high-priority

Configuration name: Akka.dispatch.UnboundedControlAwareMailbox

Unboundedprioritymailbox: The order of message delivery is equivalent to priority, non-blocking, borderless, and Unboundedstableprioritymaibox opposite

Configuration name: Akka.dispatch.UnboundedPriorityMailbox

Unboundedstableprioritymaibox: Non-blocking, borderless, FIFO delivery message

The opposite of Unboundedprioritymailbox.

Configuration name: Akka.dispatch.UnboundedStablePriorityMaibox

Boundedmailbox: The push data cannot be continued as long as the boundary limit is reached

Configuration name: bounded or Akka.dispatch.BoundedMailbox

Boundedprioritymailbox: The order of message delivery is equivalent to priority, non-blocking, bounded

Configuration name: Akka.dispatch.BoundedPriorityMailbox

Boundedstableprioritymailbox: FIFO order delivery message, non-blocking, with border

Configuration name: Akka.dispatch.BoundedStablePriorityMailbox

Boundedcontrolawaremailbox: Non-blocking, bounded, high-priority

Configuration name: Akka.dispatch.BoundedControlAwareMailbox

2.2 How to choose the mailbox type

# default is Default mailbox = Akka.actor.default-mailbox is used

How to set the default Mailboxtype.

Akka.actor.default-mailbox {

Mailbox-type= "akka.dispatch.SingleConsumerOnlyUnbounded

Mailbox "

}

# If the actor's deployment configuration segment contains a mailbox configuration segment and then describes the type of mailbox in it, then this type will be used

# If the actor's Props#withmailbox can also be set mailbox type

# If the configuration section of the dispatcher describes the Mailbox-type, then this type will be used

2.3 Custom Mailbox

Import Java.util.concurrent.ConcurrentLinkedQueue
Import Akka.actor. {actorref, Poisonpill, Actorsystem}
Import Akka.dispatch._
Import Com.typesafe.config.Config

Trait Myunboundedmessagequeuesemantics
Class Myunboundedmailbox extends Mailboxtype with producesmessagequeue[myunboundedmailbox.mymessagequeue]{
Import Myunboundedmailbox._
def this (settings:actorsystem.settings,config:config) {
This ()
}
Override Def create (Owner:option[actorref], System:option[actorsystem]): MessageQueue = {
New myMessageQueue ()
}
}

Object Myunboundedmailbox {
Class myMessageQueue extends MessageQueue with myunboundedmessagequeuesemantics {
Private Finalval queue = new Concurrentlinkedqueue[envelope] ()
Override Def enqueue (Receiver:actorref, handle:envelope): Unit = {
Queue.offer (handle)
}
Override Def Numberofmessages:int = Queue.size
Override Def dequeue (): Envelope = Queue.poll ()
Override Def cleanUp (Owner:actorref, deadletters:messagequeue): Unit = {
while (hasmessages) {
Deadletters.enqueue (Owner,dequeue ())
}
}
Override Def Hasmessages:boolean =!queue.isempty
}
}

Custom-dispatcher {
mailbox-requirement = "Com.concurrent.akka.mailbox.MyUnboundedMessageQueueSemantics"
}
akka.actor.mailbox.requirements {
"com.concurrent.akka.mailbox.MyUnboundedMessageQueueSemantics" = Custom-dispatcher-mainbox
}
custom-dispatcher-mainbox {
Mailbox-type = " Com.concurrent.akka.mailbox.MyUnboundedMailBox "
}

three-Route Routing

We know that when a large number of actors are working in parallel, processing the incoming message flow requires a component or something to boot the message from the source to the destination actor, which is a component or something that is router

In Akka, router is also an actor type, it routes incoming messages to other actors, and the other actors are called routees (routed objects)

3.1Akka Router supports the following routing policies

2.11 way before = =

# Roundrobinrouter: Polling

# Radnomrouter: Random

# Smallestmailboxrouter: Idle

# Broadcastrouter: Broadcast, the same message will be forwarded to each of the Routees

The provided routing implementation after 2.11:

# Roundrobinroutelogic

# Randomroutelogic

# Smallestmailboxroutinglogic

# Broadcastroutinglogic

# Tailchoppingroutinglogic

# Consistenthashingroutinglogic

3.2 2 ways to create router

We create router,router that can contain the actor that needs to be routed to Routees

and routing policies that route to these Routees

3.2.1 Program Dynamic Creation

Class Master extends actor{
var Router:router = _
@throws [Exception] (Classof[exception])

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.