Merge pull request #765 from akka/wip-2413-pdf-adapt-code-samples-ban

#2413 Adapt Code Samples for PDF
This commit is contained in:
Björn Antonsson 2012-10-02 02:16:54 -07:00
commit a7adfce7e5
87 changed files with 1241 additions and 814 deletions

View file

@ -40,7 +40,8 @@ class CustomRouteSpec extends AkkaSpec {
val target = system.actorOf(Props.empty)
val router = system.actorOf(Props.empty.withRouter(new MyRouter(target)))
val route = ExtractRoute(router)
val r = Await.result(router.ask(CurrentRoutees)(1 second).mapTo[RouterRoutees], 1 second)
val r = Await.result(router.ask(CurrentRoutees)(1 second).
mapTo[RouterRoutees], 1 second)
r.routees.size must be(1)
route(testActor -> "hallo") must be(Seq(Destination(testActor, target)))
route(testActor -> 12) must be(Seq(Destination(testActor, r.routees.head)))

View file

@ -626,8 +626,10 @@ class RoutingSpec extends AkkaSpec(RoutingSpec.config) with DefaultTimeout with
//#crRoute
def createRoute(routeeProvider: RouteeProvider): Route = {
val democratActor = routeeProvider.context.actorOf(Props(new DemocratActor()), "d")
val republicanActor = routeeProvider.context.actorOf(Props(new RepublicanActor()), "r")
val democratActor =
routeeProvider.context.actorOf(Props(new DemocratActor()), "d")
val republicanActor =
routeeProvider.context.actorOf(Props(new RepublicanActor()), "r")
val routees = Vector[ActorRef](democratActor, republicanActor)
//#crRegisterRoutees

View file

@ -38,10 +38,11 @@ akka {
# See the Akka Documentation for more info about Extensions
extensions = []
# Toggles whether the threads created by this ActorSystem should be daemons or not
# Toggles whether threads created by this ActorSystem should be daemons or not
daemonic = off
# JVM shutdown, System.exit(-1), in case of a fatal error, such as OutOfMemoryError
# JVM shutdown, System.exit(-1), in case of a fatal error,
# such as OutOfMemoryError
jvm-exit-on-fatal-error = on
actor {
@ -50,15 +51,15 @@ akka {
# another one is akka.remote.RemoteActorRefProvider in the akka-remote bundle.
provider = "akka.actor.LocalActorRefProvider"
# The guardian "/user" will use this subclass of akka.actor.SupervisorStrategyConfigurator
# to obtain its supervisorStrategy. Besides the default there is
# akka.actor.StoppingSupervisorStrategy
# The guardian "/user" will use this class to obtain its supervisorStrategy.
# It needs to be a subclass of akka.actor.SupervisorStrategyConfigurator.
# In addition to the default there is akka.actor.StoppingSupervisorStrategy.
guardian-supervisor-strategy = "akka.actor.DefaultSupervisorStrategy"
# Timeout for ActorSystem.actorOf
creation-timeout = 20s
# frequency with which stopping actors are prodded in case they had to be
# Frequency with which stopping actors are prodded in case they had to be
# removed from their parents
reaper-interval = 5s
@ -66,12 +67,13 @@ akka {
# this is only intended for testing.
serialize-messages = off
# Serializes and deserializes creators (in Props) to ensure that they can be sent over the network,
# this is only intended for testing.
# Serializes and deserializes creators (in Props) to ensure that they can be
# sent over the network, this is only intended for testing.
serialize-creators = off
# Timeout for send operations to top-level actors which are in the process of being started.
# This is only relevant if using a bounded mailbox or the CallingThreadDispatcher for a top-level actor.
# Timeout for send operations to top-level actors which are in the process
# of being started. This is only relevant if using a bounded mailbox or the
# CallingThreadDispatcher for a top-level actor.
unstarted-push-timeout = 10s
typed {
@ -85,24 +87,28 @@ akka {
default {
# routing (load-balance) scheme to use
# available: "from-code", "round-robin", "random", "smallest-mailbox", "scatter-gather", "broadcast"
# or: Fully qualified class name of the router class.
# The router class must extend akka.routing.CustomRouterConfig and and have constructor
# with com.typesafe.config.Config parameter.
# default is "from-code";
# Whether or not an actor is transformed to a Router is decided in code only (Props.withRouter).
# The type of router can be overridden in the configuration; specifying "from-code" means
# that the values specified in the code shall be used.
# - available: "from-code", "round-robin", "random", "smallest-mailbox",
# "scatter-gather", "broadcast"
# - or: Fully qualified class name of the router class.
# The class must extend akka.routing.CustomRouterConfig and
# have a constructor with com.typesafe.config.Config
# parameter.
# - default is "from-code";
# Whether or not an actor is transformed to a Router is decided in code
# only (Props.withRouter). The type of router can be overridden in the
# configuration; specifying "from-code" means that the values specified
# in the code shall be used.
# In case of routing, the actors to be routed to can be specified
# in several ways:
# - nr-of-instances: will create that many children
# - routees.paths: will look the paths up using actorFor and route to
# them, i.e. will not create children
# - resizer: dynamically resizable number of routees as specified in resizer below
# - resizer: dynamically resizable number of routees as specified in
# resizer below
router = "from-code"
# number of children to create in case of a non-direct router; this setting
# is ignored if routees.paths is given
# number of children to create in case of a non-direct router;
# this setting is ignored if routees.paths is given
nr-of-instances = 1
# within is the timeout used for routers containing future calls
@ -118,8 +124,8 @@ akka {
paths = []
}
# Routers with dynamically resizable number of routees; this feature is enabled
# by including (parts of) this section in the deployment
# Routers with dynamically resizable number of routees; this feature is
# enabled by including (parts of) this section in the deployment
resizer {
# The fewest number of routees the router should ever have.
@ -129,8 +135,8 @@ akka {
# Must be greater than or equal to lower-bound.
upper-bound = 10
# Threshold to evaluate if routee is considered to be busy (under pressure).
# Implementation depends on this value (default is 1).
# Threshold used to evaluate if a routee is considered to be busy
# (under pressure). Implementation depends on this value (default is 1).
# 0: number of routees currently processing a message.
# 1: number of routees currently processing a message has
# some messages in mailbox.
@ -158,9 +164,10 @@ akka {
# capacity is 9 it will request an decrease of 1 routee.
backoff-rate = 0.1
# When the resizer reduce the capacity the abandoned routee actors are stopped
# with PoisonPill after this delay. The reason for the delay is to give concurrent
# messages a chance to be placed in mailbox before sending PoisonPill.
# When the resizer reduce the capacity the abandoned routee actors are
# stopped with PoisonPill after this delay. The reason for the delay is
# to give concurrent messages a chance to be placed in mailbox before
# sending PoisonPill.
# Use 0s to skip delay.
stop-delay = 1s
@ -178,20 +185,19 @@ akka {
default-dispatcher {
# Must be one of the following
# Dispatcher, (BalancingDispatcher, only valid when all actors using it are of
# the same type), PinnedDispatcher, or a FQCN to a class inheriting
# Dispatcher, (BalancingDispatcher, only valid when all actors using it are
# of the same type), PinnedDispatcher, or a FQCN to a class inheriting
# MessageDispatcherConfigurator with a constructor with
# com.typesafe.config.Config parameter and akka.dispatch.DispatcherPrerequisites
# parameters.
# both com.typesafe.config.Config parameter and
# akka.dispatch.DispatcherPrerequisites parameters.
# PinnedDispatcher must be used toghether with executor=thread-pool-executor.
type = "Dispatcher"
# Which kind of ExecutorService to use for this dispatcher
# Valid options:
# "fork-join-executor" requires a "fork-join-executor" section
# "thread-pool-executor" requires a "thread-pool-executor" section
# or
# A FQCN of a class extending ExecutorServiceConfigurator
# - "fork-join-executor" requires a "fork-join-executor" section
# - "thread-pool-executor" requires a "thread-pool-executor" section
# - A FQCN of a class extending ExecutorServiceConfigurator
executor = "fork-join-executor"
# This will be used if you have set "executor = "fork-join-executor""
@ -199,9 +205,9 @@ akka {
# Min number of threads to cap factor-based parallelism number to
parallelism-min = 8
# The parallelism factor is used to determine thread pool size using the following formula:
# ceil(available processors * factor). Resulting size is then bounded by the parallelism-min
# and parallelism-max values.
# The parallelism factor is used to determine thread pool size using the
# following formula: ceil(available processors * factor). Resulting size
# is then bounded by the parallelism-min and parallelism-max values.
parallelism-factor = 3.0
# Max number of threads to cap factor-based parallelism number to
@ -216,22 +222,25 @@ akka {
# Min number of threads to cap factor-based core number to
core-pool-size-min = 8
# The core pool size factor is used to determine thread pool core size using the following formula:
# ceil(available processors * factor). Resulting size is then bounded by the core-pool-size-min
# and core-pool-size-max values.
# The core pool size factor is used to determine thread pool core size
# using the following formula: ceil(available processors * factor).
# Resulting size is then bounded by the core-pool-size-min and
# core-pool-size-max values.
core-pool-size-factor = 3.0
# Max number of threads to cap factor-based number to
core-pool-size-max = 64
# Minimum number of threads to cap factor-based max number to (if using a bounded task queue)
# Minimum number of threads to cap factor-based max number to
# (if using a bounded task queue)
max-pool-size-min = 8
# Max no of threads (if using a bounded task queue) is determined by calculating:
# ceil(available processors * factor)
# Max no of threads (if using a bounded task queue) is determined by
# calculating: ceil(available processors * factor)
max-pool-size-factor = 3.0
# Max number of threads to cap factor-based max number to (if using a bounded task queue)
# Max number of threads to cap factor-based max number to
# (if using a bounded task queue)
max-pool-size-max = 64
# Specifies the bounded capacity of the task queue (< 1 == unbounded)
@ -256,12 +265,12 @@ akka {
throughput-deadline-time = 0ms
# If negative (or zero) then an unbounded mailbox is used (default)
# If positive then a bounded mailbox is used and the capacity is set using the
# property
# NOTE: setting a mailbox to 'blocking' can be a bit dangerous, could lead to
# deadlock, use with care
# The following mailbox-push-timeout-time is only used for type=Dispatcher and
# only if mailbox-capacity > 0
# If positive then a bounded mailbox is used and the capacity is set using
# the property
# NOTE: setting a mailbox to 'blocking' can be a bit dangerous, could lead
# to deadlock, use with care
# The following mailbox-push-timeout-time is only used for type=Dispatcher
# and only if mailbox-capacity > 0
mailbox-capacity = -1
# Specifies the timeout to add a new message to a mailbox that is full -
@ -281,18 +290,18 @@ akka {
# For Actor with Stash: The default capacity of the stash.
# If negative (or zero) then an unbounded stash is used (default)
# If positive then a bounded stash is used and the capacity is set using the
# property
# If positive then a bounded stash is used and the capacity is set using
# the property
stash-capacity = -1
}
debug {
# enable function of Actor.loggable(), which is to log any received message at
# DEBUG level, see the “Testing Actor Systems” section of the Akka Documentation
# at http://akka.io/docs
# enable function of Actor.loggable(), which is to log any received message
# at DEBUG level, see the “Testing Actor Systems” section of the Akka
# Documentation at http://akka.io/docs
receive = off
# enable DEBUG logging of all AutoReceiveMessages (Kill, PoisonPill and the like)
# enable DEBUG logging of all AutoReceiveMessages (Kill, PoisonPill et.c.)
autoreceive = off
# enable DEBUG logging of actor lifecycle changes
@ -317,9 +326,10 @@ akka {
bytes = "akka.serialization.ByteArraySerializer"
}
# Class to Serializer binding. You only need to specify the name of an interface
# or abstract base class of the messages. In case of ambiguity it is using the
# most specific configured class, or giving a warning and choosing the “first” one.
# Class to Serializer binding. You only need to specify the name of an
# interface or abstract base class of the messages. In case of ambiguity it
# is using the most specific configured class, or giving a warning and
# choosing the “first” one.
#
# To disable one of the default serializers, assign its class to "none", like
# "java.io.Serializable" = none
@ -330,8 +340,8 @@ akka {
# Configuration items which are used by the akka.actor.ActorDSL._ methods
dsl {
# Maximum queue size of the actor created by newInbox(); this protects against
# faulty programs which use select() and consistently miss messages
# Maximum queue size of the actor created by newInbox(); this protects
# against faulty programs which use select() and consistently miss messages
inbox-size = 1000
# Default timeout to assume for operations like Inbox.receive et al
@ -340,16 +350,18 @@ akka {
}
# Used to set the behavior of the scheduler.
# Changing the default values may change the system behavior drastically so make sure
# you know what you're doing! See the Scheduler section of the Akka documentation for more details.
# Changing the default values may change the system behavior drastically so make
# sure you know what you're doing! See the Scheduler section of the Akka
# Documentation for more details.
scheduler {
# The HashedWheelTimer (HWT) implementation from Netty is used as the default scheduler
# in the system.
# The HashedWheelTimer (HWT) implementation from Netty is used as the default
# scheduler in the system.
# HWT does not execute the scheduled tasks on exact time.
# It will, on every tick, check if there are any tasks behind the schedule and execute them.
# You can increase or decrease the accuracy of the execution timing by specifying smaller
# or larger tick duration.
# If you are scheduling a lot of tasks you should consider increasing the ticks per wheel.
# It will, on every tick, check if there are any tasks behind the schedule
# and execute them. You can increase or decrease the accuracy of the execution
# timing by specifying smaller or larger tick duration.
# If you are scheduling a lot of tasks you should consider increasing the
# ticks per wheel.
# For more information see: http://www.jboss.org/netty/
tick-duration = 100ms
ticks-per-wheel = 512

View file

@ -49,7 +49,8 @@ trait Scheduler {
* Scala API
*/
def schedule(
initialDelay: FiniteDuration, interval: FiniteDuration)(f: Unit)(implicit executor: ExecutionContext): Cancellable
initialDelay: FiniteDuration,
interval: FiniteDuration)(f: Unit)(implicit executor: ExecutionContext): Cancellable
/**
* Schedules a function to be run repeatedly with an initial delay and
@ -60,7 +61,9 @@ trait Scheduler {
* Java API
*/
def schedule(
initialDelay: FiniteDuration, interval: FiniteDuration, runnable: Runnable)(implicit executor: ExecutionContext): Cancellable
initialDelay: FiniteDuration,
interval: FiniteDuration,
runnable: Runnable)(implicit executor: ExecutionContext): Cancellable
/**
* Schedules a Runnable to be run once with a delay, i.e. a time period that
@ -68,7 +71,9 @@ trait Scheduler {
*
* Java & Scala API
*/
def scheduleOnce(delay: FiniteDuration, runnable: Runnable)(implicit executor: ExecutionContext): Cancellable
def scheduleOnce(
delay: FiniteDuration,
runnable: Runnable)(implicit executor: ExecutionContext): Cancellable
/**
* Schedules a message to be sent once with a delay, i.e. a time period that has
@ -76,7 +81,10 @@ trait Scheduler {
*
* Java & Scala API
*/
def scheduleOnce(delay: FiniteDuration, receiver: ActorRef, message: Any)(implicit executor: ExecutionContext): Cancellable
def scheduleOnce(
delay: FiniteDuration,
receiver: ActorRef,
message: Any)(implicit executor: ExecutionContext): Cancellable
/**
* Schedules a function to be run once with a delay, i.e. a time period that has
@ -84,7 +92,8 @@ trait Scheduler {
*
* Scala API
*/
def scheduleOnce(delay: FiniteDuration)(f: Unit)(implicit executor: ExecutionContext): Cancellable
def scheduleOnce(
delay: FiniteDuration)(f: Unit)(implicit executor: ExecutionContext): Cancellable
}
//#scheduler

View file

@ -8,7 +8,8 @@
akka {
cluster {
# Initial contact points of the cluster. Nodes to join at startup if auto-join = on.
# Initial contact points of the cluster.
# The nodes to join at startup if auto-join = on.
# Comma separated full URIs defined by a string on the form of
# "akka://system@hostname:port"
# Leave as empty if the node should be a singleton cluster.
@ -21,16 +22,17 @@ akka {
# If seed-nodes is empty it will join itself and become a single node cluster.
auto-join = on
# Should the 'leader' in the cluster be allowed to automatically mark unreachable
# nodes as DOWN?
# Using auto-down implies that two separate clusters will automatically be formed
# in case of network partition.
# Should the 'leader' in the cluster be allowed to automatically mark
# unreachable nodes as DOWN?
# Using auto-down implies that two separate clusters will automatically be
# formed in case of network partition.
auto-down = off
# Enable or disable JMX MBeans for management of the cluster
jmx.enabled = on
# how long should the node wait before starting the periodic tasks maintenance tasks?
# how long should the node wait before starting the periodic tasks
# maintenance tasks?
periodic-tasks-initial-delay = 1s
# how often should the node send out gossip information?
@ -39,8 +41,8 @@ akka {
# how often should the leader perform maintenance tasks?
leader-actions-interval = 1s
# how often should the node move nodes, marked as unreachable by the failure detector,
# out of the membership ring?
# how often should the node move nodes, marked as unreachable by the failure
# detector, out of the membership ring?
unreachable-nodes-reaper-interval = 1s
# How often the current internal stats should be published.
@ -56,7 +58,7 @@ akka {
# If specified you need to define the settings of the actual dispatcher.
use-dispatcher = ""
# Gossip to random node with newer or older state information, if any with some
# Gossip to random node with newer or older state information, if any with
# this probability. Otherwise Gossip to any random live node.
# Probability value is between 0.0 and 1.0. 0.0 means never, 1.0 means always.
gossip-different-view-probability = 0.8
@ -111,15 +113,16 @@ akka {
# How often a node publishes metrics information.
gossip-interval = 3s
# How quickly the exponential weighting of past data is decayed compared to new data.
# How quickly the exponential weighting of past data is decayed compared to
# new data.
# If set to 0 data streaming over time will be turned off.
# Set higher to increase the bias toward newer values
rate-of-decay = 10
}
# If the tick-duration of the default scheduler is longer than the tick-duration
# configured here a dedicated scheduler will be used for periodic tasks of the cluster,
# otherwise the default scheduler is used.
# If the tick-duration of the default scheduler is longer than the
# tick-duration configured here a dedicated scheduler will be used for
# periodic tasks of the cluster, otherwise the default scheduler is used.
# See akka.scheduler settings for more details about the HashedWheelTimer.
scheduler {
tick-duration = 33ms

View file

@ -21,63 +21,63 @@ import java.util.concurrent.Callable;
//#circuit-breaker-initialization
public class DangerousJavaActor extends UntypedActor {
private final CircuitBreaker breaker;
private final LoggingAdapter log = Logging.getLogger(getContext().system(), this);
private final CircuitBreaker breaker;
private final LoggingAdapter log = Logging.getLogger(getContext().system(), this);
public DangerousJavaActor() {
this.breaker = new CircuitBreaker(
getContext().dispatcher(), getContext().system().scheduler(),
5, Duration.create(10, "s"), Duration.create(1, "m"))
.onOpen(new Callable<Object>() {
public Object call() throws Exception {
notifyMeOnOpen();
return null;
}
});
}
public DangerousJavaActor() {
this.breaker = new CircuitBreaker(
getContext().dispatcher(), getContext().system().scheduler(),
5, Duration.create(10, "s"), Duration.create(1, "m"))
.onOpen(new Callable<Object>() {
public Object call() throws Exception {
notifyMeOnOpen();
return null;
}
});
}
public void notifyMeOnOpen() {
log.warning("My CircuitBreaker is now open, and will not close for one minute");
}
public void notifyMeOnOpen() {
log.warning("My CircuitBreaker is now open, and will not close for one minute");
}
//#circuit-breaker-initialization
//#circuit-breaker-usage
public String dangerousCall() {
return "This really isn't that dangerous of a call after all";
}
//#circuit-breaker-usage
public String dangerousCall() {
return "This really isn't that dangerous of a call after all";
}
@Override
public void onReceive(Object message) {
if (message instanceof String) {
String m = (String) message;
if ("is my middle name".equals(m)) {
final Future<String> f = future(
new Callable<String>() {
public String call() {
return dangerousCall();
}
}, getContext().dispatcher());
@Override
public void onReceive(Object message) {
if (message instanceof String) {
String m = (String) message;
if ("is my middle name".equals(m)) {
final Future<String> f = future(
new Callable<String>() {
public String call() {
return dangerousCall();
}
}, getContext().dispatcher());
getSender().tell(breaker
.callWithCircuitBreaker(
new Callable<Future<String>>() {
public Future<String> call() throws Exception {
return f;
}
}), getSelf());
}
if ("block for me".equals(m)) {
getSender().tell(breaker
.callWithSyncCircuitBreaker(
new Callable<String>() {
@Override
public String call() throws Exception {
return dangerousCall();
}
}), getSelf());
}
}
getSender().tell(breaker
.callWithCircuitBreaker(
new Callable<Future<String>>() {
public Future<String> call() throws Exception {
return f;
}
}), getSelf());
}
if ("block for me".equals(m)) {
getSender().tell(breaker
.callWithSyncCircuitBreaker(
new Callable<String>() {
@Override
public String call() throws Exception {
return dangerousCall();
}
}), getSelf());
}
}
}
//#circuit-breaker-usage
}

View file

@ -12,7 +12,7 @@ object Scala {
val threemillis = 3.millis
val diff = fivesec - threemillis
assert(diff < fivesec)
val fourmillis = threemillis * 4 / 3 // though you cannot write it the other way around
val fourmillis = threemillis * 4 / 3 // you cannot write it the other way around
val n = threemillis / (1 millisecond)
//#dsl

View file

@ -32,7 +32,7 @@ Please follow these guidelines when creating public commits and writing commit m
Example::
Completed replication over BookKeeper based transaction log with configurable actor snapshotting every X message. Fixes #XXX
Completed replication over BookKeeper based transaction log. Fixes #XXX
* Details 1
* Details 2
@ -63,4 +63,4 @@ with main methods) and running ScalaTest tests.
NetworkFailureTest
^^^^^^^^^^^^^^^^^^
You can use the 'NetworkFailureTest' trait to test network failure.
You can use the 'NetworkFailureTest' trait to test network failure.

View file

@ -33,18 +33,21 @@ multi-JVM testing (Simplified for clarity):
lazy val remoteTests = Project(
id = "akka-remote-tests",
base = file("akka-remote-tests"),
dependencies = Seq(remote, actorTests % "test->test", testkit % "test->test"),
dependencies = Seq(remote, actorTests % "test->test",
testkit % "test->test"),
settings = defaultSettings ++ Seq(
// disable parallel tests
parallelExecution in Test := false,
extraOptions in MultiJvm <<= (sourceDirectory in MultiJvm) { src =>
(name: String) => (src ** (name + ".conf")).get.headOption.map("-Dakka.config=" + _.absolutePath).toSeq
(name: String) => (src ** (name + ".conf")).get.
headOption.map("-Dakka.config=" + _.absolutePath).toSeq
},
test in Test <<= (test in Test) dependsOn (test in MultiJvm)
)
) configs (MultiJvm)
lazy val buildSettings = Defaults.defaultSettings ++ SbtMultiJvm.multiJvmSettings ++ Seq(
lazy val buildSettings = Defaults.defaultSettings ++
SbtMultiJvm.multiJvmSettings ++ Seq(
organization := "com.typesafe.akka",
version := "@version@",
scalaVersion := "@scalaVersion@",

View file

@ -98,9 +98,9 @@ Each actor path has an address component, describing the protocol and location
by which the corresponding actor is reachable, followed by the names of the
actors in the hierarchy from the root up. Examples are::
"akka://my-system/user/service-a/worker1" // purely local
"akka://my-system@serv.example.com:5678/user/service-b" // local or remote
"cluster://my-cluster/service-c" // clustered (Future Extension)
"akka://my-sys/user/service-a/worker1" // purely local
"akka://my-sys@host.example.com:5678/user/service-b" // local or remote
"cluster://my-cluster/service-c" // clustered (Future Extension)
Here, ``akka`` is the default remote protocol for the 2.0 release, and others
are pluggable. The interpretation of the host & port part (i.e.

View file

@ -224,7 +224,8 @@ differentiate actor systems within the hierarchy of the configuration::
val config = ConfigFactory.load()
val app1 = ActorSystem("MyApp1", config.getConfig("myapp1").withFallback(config))
val app2 = ActorSystem("MyApp2", config.getConfig("myapp2").withOnlyPath("akka").withFallback(config))
val app2 = ActorSystem("MyApp2",
config.getConfig("myapp2").withOnlyPath("akka").withFallback(config))
These two samples demonstrate different variations of the “lift-a-subtree”
trick: in the first case, the configuration accessible from within the actor

View file

@ -22,8 +22,9 @@ import akka.testkit.AkkaSpec;
public class FSMDocTestBase {
static
//#data
public static final class SetTarget {
public final class SetTarget {
final ActorRef ref;
public SetTarget(ActorRef ref) {
@ -31,7 +32,10 @@ public class FSMDocTestBase {
}
}
public static final class Queue {
//#data
static
//#data
public final class Queue {
final Object o;
public Queue(Object o) {
@ -39,9 +43,15 @@ public class FSMDocTestBase {
}
}
public static final Object flush = new Object();
//#data
static
//#data
public final Object flush = new Object();
public static final class Batch {
//#data
static
//#data
public final class Batch {
final List<Object> objects;
public Batch(List<Object> objects) {
@ -51,8 +61,9 @@ public class FSMDocTestBase {
//#data
static
//#base
static abstract class MyFSMBase extends UntypedActor {
public abstract class MyFSMBase extends UntypedActor {
/*
* This is the mutable state of this state machine.
@ -118,10 +129,12 @@ public class FSMDocTestBase {
//#base
static
//#actor
static public class MyFSM extends MyFSMBase {
public class MyFSM extends MyFSMBase {
private final LoggingAdapter log = Logging.getLogger(getContext().system(), this);
private final LoggingAdapter log =
Logging.getLogger(getContext().system(), this);
@Override
public void onReceive(Object o) {

View file

@ -35,11 +35,13 @@ import org.junit.AfterClass;
//#testkit
public class FaultHandlingTestBase {
//#testkit
static
//#supervisor
static public class Supervisor extends UntypedActor {
public class Supervisor extends UntypedActor {
//#strategy
private static SupervisorStrategy strategy = new OneForOneStrategy(10, Duration.parse("1 minute"),
private static SupervisorStrategy strategy =
new OneForOneStrategy(10, Duration.parse("1 minute"),
new Function<Throwable, Directive>() {
@Override
public Directive apply(Throwable t) {
@ -73,11 +75,13 @@ public class FaultHandlingTestBase {
//#supervisor
static
//#supervisor2
static public class Supervisor2 extends UntypedActor {
public class Supervisor2 extends UntypedActor {
//#strategy2
private static SupervisorStrategy strategy = new OneForOneStrategy(10, Duration.parse("1 minute"),
private static SupervisorStrategy strategy = new OneForOneStrategy(10,
Duration.parse("1 minute"),
new Function<Throwable, Directive>() {
@Override
public Directive apply(Throwable t) {
@ -116,8 +120,9 @@ public class FaultHandlingTestBase {
//#supervisor2
static
//#child
static public class Child extends UntypedActor {
public class Child extends UntypedActor {
int state = 0;
public void onReceive(Object o) throws Exception {
@ -163,7 +168,8 @@ public class FaultHandlingTestBase {
//#create
Props superprops = new Props(Supervisor.class);
ActorRef supervisor = system.actorOf(superprops, "supervisor");
ActorRef child = (ActorRef) Await.result(ask(supervisor, new Props(Child.class), 5000), timeout);
ActorRef child = (ActorRef) Await.result(ask(supervisor,
new Props(Child.class), 5000), timeout);
//#create
//#resume
@ -186,7 +192,8 @@ public class FaultHandlingTestBase {
//#stop
//#escalate-kill
child = (ActorRef) Await.result(ask(supervisor, new Props(Child.class), 5000), timeout);
child = (ActorRef) Await.result(ask(supervisor,
new Props(Child.class), 5000), timeout);
probe.watch(child);
assert Await.result(ask(child, "get", 5000), timeout).equals(0);
child.tell(new Exception(), null);
@ -196,7 +203,8 @@ public class FaultHandlingTestBase {
//#escalate-restart
superprops = new Props(Supervisor2.class);
supervisor = system.actorOf(superprops);
child = (ActorRef) Await.result(ask(supervisor, new Props(Child.class), 5000), timeout);
child = (ActorRef) Await.result(ask(supervisor,
new Props(Child.class), 5000), timeout);
child.tell(23, null);
assert Await.result(ask(child, "get", 5000), timeout).equals(23);
child.tell(new Exception(), null);
@ -207,7 +215,8 @@ public class FaultHandlingTestBase {
//#testkit
public <A> Seq<A> seq(A... args) {
return JavaConverters.collectionAsScalaIterableConverter(java.util.Arrays.asList(args)).asScala().toSeq();
return JavaConverters.collectionAsScalaIterableConverter(
java.util.Arrays.asList(args)).asScala().toSeq();
}
//#testkit
}

View file

@ -7,14 +7,12 @@ package docs.actor;
import akka.actor.Props;
import scala.concurrent.util.Duration;
import java.util.concurrent.TimeUnit;
//#imports1
//#imports2
import akka.actor.UntypedActor;
import akka.actor.UntypedActorFactory;
import akka.actor.Cancellable;
//#imports2
import akka.actor.ActorRef;
@ -44,17 +42,17 @@ public class SchedulerDocTestBase {
@Test
public void scheduleOneOffTask() {
//#schedule-one-off-message
//Schedules to send the "foo"-message to the testActor after 50ms
system.scheduler().scheduleOnce(Duration.create(50, TimeUnit.MILLISECONDS), testActor, "foo", system.dispatcher());
system.scheduler().scheduleOnce(Duration.create(50, TimeUnit.MILLISECONDS),
testActor, "foo", system.dispatcher());
//#schedule-one-off-message
//#schedule-one-off-thunk
//Schedules a Runnable to be executed (send the current time) to the testActor after 50ms
system.scheduler().scheduleOnce(Duration.create(50, TimeUnit.MILLISECONDS), new Runnable() {
@Override
public void run() {
testActor.tell(System.currentTimeMillis(), null);
}
system.scheduler().scheduleOnce(Duration.create(50, TimeUnit.MILLISECONDS),
new Runnable() {
@Override
public void run() {
testActor.tell(System.currentTimeMillis(), null);
}
}, system.dispatcher());
//#schedule-one-off-thunk
}
@ -62,24 +60,26 @@ public class SchedulerDocTestBase {
@Test
public void scheduleRecurringTask() {
//#schedule-recurring
ActorRef tickActor = system.actorOf(new Props().withCreator(new UntypedActorFactory() {
public UntypedActor create() {
return new UntypedActor() {
public void onReceive(Object message) {
if (message.equals("Tick")) {
// Do someting
} else {
unhandled(message);
ActorRef tickActor = system.actorOf(new Props().withCreator(
new UntypedActorFactory() {
public UntypedActor create() {
return new UntypedActor() {
public void onReceive(Object message) {
if (message.equals("Tick")) {
// Do someting
} else {
unhandled(message);
}
}
}
};
}
}));
};
}
}));
//This will schedule to send the Tick-message
//to the tickActor after 0ms repeating every 50ms
Cancellable cancellable = system.scheduler().schedule(Duration.Zero(), Duration.create(50, TimeUnit.MILLISECONDS),
tickActor, "Tick", system.dispatcher());
Cancellable cancellable = system.scheduler().schedule(Duration.Zero(),
Duration.create(50, TimeUnit.MILLISECONDS), tickActor, "Tick",
system.dispatcher());
//This cancels further Ticks to be sent
cancellable.cancel();

View file

@ -23,8 +23,9 @@ public class TypedActorDocTestBase {
Object someReference = null;
ActorSystem system = null;
static
//#typed-actor-iface
public static interface Squarer {
public interface Squarer {
//#typed-actor-iface-methods
void squareDontCare(int i); //fire-forget
@ -37,8 +38,9 @@ public class TypedActorDocTestBase {
}
//#typed-actor-iface
static
//#typed-actor-impl
static class SquarerImpl implements Squarer {
class SquarerImpl implements Squarer {
private String name;
public SquarerImpl() {
@ -107,14 +109,16 @@ public class TypedActorDocTestBase {
try {
//#typed-actor-create1
Squarer mySquarer =
TypedActor.get(system).typedActorOf(new TypedProps<SquarerImpl>(Squarer.class, SquarerImpl.class));
TypedActor.get(system).typedActorOf(
new TypedProps<SquarerImpl>(Squarer.class, SquarerImpl.class));
//#typed-actor-create1
//#typed-actor-create2
Squarer otherSquarer =
TypedActor.get(system).typedActorOf(new TypedProps<SquarerImpl>(Squarer.class,
new Creator<SquarerImpl>() {
public SquarerImpl create() { return new SquarerImpl("foo"); }
}),
TypedActor.get(system).typedActorOf(
new TypedProps<SquarerImpl>(Squarer.class,
new Creator<SquarerImpl>() {
public SquarerImpl create() { return new SquarerImpl("foo"); }
}),
"name");
//#typed-actor-create2
@ -136,7 +140,8 @@ public class TypedActorDocTestBase {
//#typed-actor-call-strict
//#typed-actor-calls
assertEquals(100, Await.result(fSquare, Duration.create(3, TimeUnit.SECONDS)).intValue());
assertEquals(100, Await.result(fSquare,
Duration.create(3, TimeUnit.SECONDS)).intValue());
assertEquals(100, oSquare.get().intValue());
@ -150,26 +155,26 @@ public class TypedActorDocTestBase {
TypedActor.get(system).poisonPill(otherSquarer);
//#typed-actor-poisonpill
} catch(Exception e) {
//Ignore
//Ignore
}
}
@Test public void createHierarchies() {
try {
//#typed-actor-hierarchy
Squarer childSquarer =
TypedActor.get(TypedActor.context()).
typedActorOf(
new TypedProps<SquarerImpl>(Squarer.class, SquarerImpl.class)
);
//Use "childSquarer" as a Squarer
//#typed-actor-hierarchy
} catch (Exception e) {
//dun care
}
@Test public void createHierarchies() {
try {
//#typed-actor-hierarchy
Squarer childSquarer =
TypedActor.get(TypedActor.context()).
typedActorOf(
new TypedProps<SquarerImpl>(Squarer.class, SquarerImpl.class)
);
//Use "childSquarer" as a Squarer
//#typed-actor-hierarchy
} catch (Exception e) {
//dun care
}
}
@Test public void proxyAnyActorRef() {
@Test public void proxyAnyActorRef() {
try {
//#typed-actor-remote
Squarer typedActor =

View file

@ -122,7 +122,8 @@ public class UntypedActorDocTestBase {
public void propsActorOf() {
ActorSystem system = ActorSystem.create("MySystem");
//#creating-props
ActorRef myActor = system.actorOf(new Props(MyUntypedActor.class).withDispatcher("my-dispatcher"), "myactor");
ActorRef myActor = system.actorOf(
new Props(MyUntypedActor.class).withDispatcher("my-dispatcher"), "myactor");
//#creating-props
myActor.tell("test", null);
system.shutdown();
@ -201,7 +202,8 @@ public class UntypedActorDocTestBase {
ActorRef actorRef = system.actorOf(new Props(MyUntypedActor.class));
//#gracefulStop
try {
Future<Boolean> stopped = gracefulStop(actorRef, Duration.create(5, TimeUnit.SECONDS), system);
Future<Boolean> stopped =
gracefulStop(actorRef, Duration.create(5, TimeUnit.SECONDS), system);
Await.result(stopped, Duration.create(6, TimeUnit.SECONDS));
// the actor has been stopped
} catch (AskTimeoutException e) {
@ -234,16 +236,18 @@ public class UntypedActorDocTestBase {
futures.add(ask(actorA, "request", 1000)); // using 1000ms timeout
futures.add(ask(actorB, "another request", t)); // using timeout from above
final Future<Iterable<Object>> aggregate = Futures.sequence(futures, system.dispatcher());
final Future<Result> transformed = aggregate.map(new Mapper<Iterable<Object>, Result>() {
public Result apply(Iterable<Object> coll) {
final Iterator<Object> it = coll.iterator();
final String s = (String) it.next();
final int x = (Integer) it.next();
return new Result(x, s);
}
}, system.dispatcher());
final Future<Iterable<Object>> aggregate =
Futures.sequence(futures, system.dispatcher());
final Future<Result> transformed = aggregate.map(
new Mapper<Iterable<Object>, Result>() {
public Result apply(Iterable<Object> coll) {
final Iterator<Object> it = coll.iterator();
final String s = (String) it.next();
final int x = (Integer) it.next();
return new Result(x, s);
}
}, system.dispatcher());
pipe(transformed, system.dispatcher()).to(actorC);
//#ask-pipe
@ -305,8 +309,9 @@ public class UntypedActorDocTestBase {
}
}
static
//#hot-swap-actor
public static class HotSwapActor extends UntypedActor {
public class HotSwapActor extends UntypedActor {
Procedure<Object> angry = new Procedure<Object>() {
@Override
@ -343,8 +348,9 @@ public class UntypedActorDocTestBase {
//#hot-swap-actor
static
//#stash
public static class ActorWithProtocol extends UntypedActorWithStash {
public class ActorWithProtocol extends UntypedActorWithStash {
private Boolean isOpen = false;
public void onReceive(Object msg) {
if (isOpen) {
@ -368,11 +374,12 @@ public class UntypedActorDocTestBase {
}
//#stash
static
//#watch
public static class WatchActor extends UntypedActor {
public class WatchActor extends UntypedActor {
final ActorRef child = this.getContext().actorOf(Props.empty(), "child");
{
this.getContext().watch(child); // <-- this is the only call needed for registration
this.getContext().watch(child); // <-- the only call needed for registration
}
ActorRef lastSender = getContext().system().deadLetters();

View file

@ -39,7 +39,8 @@ public class FaultHandlingDocSample {
* Runs the sample
*/
public static void main(String[] args) {
Config config = ConfigFactory.parseString("akka.loglevel = DEBUG \n" + "akka.actor.debug.lifecycle = on");
Config config = ConfigFactory.parseString("akka.loglevel = DEBUG \n" +
"akka.actor.debug.lifecycle = on");
ActorSystem system = ActorSystem.create("FaultToleranceSample", config);
ActorRef worker = system.actorOf(new Props(Worker.class), "worker");
@ -59,7 +60,8 @@ public class FaultHandlingDocSample {
@Override
public void preStart() {
// If we don't get any progress within 15 seconds then the service is unavailable
// If we don't get any progress within 15 seconds then the service
// is unavailable
getContext().setReceiveTimeout(Duration.parse("15 seconds"));
}
@ -111,23 +113,25 @@ public class FaultHandlingDocSample {
final LoggingAdapter log = Logging.getLogger(getContext().system(), this);
final Timeout askTimeout = new Timeout(Duration.create(5, "seconds"));
// The sender of the initial Start message will continuously be notified about progress
// The sender of the initial Start message will continuously be notified
// about progress
ActorRef progressListener;
final ActorRef counterService = getContext().actorOf(new Props(CounterService.class), "counter");
final ActorRef counterService = getContext().actorOf(
new Props(CounterService.class), "counter");
final int totalCount = 51;
// Stop the CounterService child if it throws ServiceUnavailable
private static SupervisorStrategy strategy = new OneForOneStrategy(-1, Duration.Inf(),
new Function<Throwable, Directive>() {
@Override
public Directive apply(Throwable t) {
if (t instanceof ServiceUnavailable) {
return stop();
} else {
return escalate();
}
}
});
private static SupervisorStrategy strategy = new OneForOneStrategy(-1,
Duration.Inf(), new Function<Throwable, Directive>() {
@Override
public Directive apply(Throwable t) {
if (t instanceof ServiceUnavailable) {
return stop();
} else {
return escalate();
}
}
});
@Override
public SupervisorStrategy supervisorStrategy() {
@ -139,7 +143,8 @@ public class FaultHandlingDocSample {
if (msg.equals(Start) && progressListener == null) {
progressListener = getSender();
getContext().system().scheduler().schedule(
Duration.Zero(), Duration.create(1, "second"), getSelf(), Do, getContext().dispatcher()
Duration.Zero(), Duration.create(1, "second"), getSelf(), Do,
getContext().dispatcher()
);
} else if (msg.equals(Do)) {
counterService.tell(new Increment(1), getSelf());
@ -231,17 +236,17 @@ public class FaultHandlingDocSample {
// Restart the storage child when StorageException is thrown.
// After 3 restarts within 5 seconds it will be stopped.
private static SupervisorStrategy strategy = new OneForOneStrategy(3, Duration.parse("5 seconds"),
new Function<Throwable, Directive>() {
@Override
public Directive apply(Throwable t) {
if (t instanceof StorageException) {
return restart();
} else {
return escalate();
}
}
});
private static SupervisorStrategy strategy = new OneForOneStrategy(3,
Duration.parse("5 seconds"), new Function<Throwable, Directive>() {
@Override
public Directive apply(Throwable t) {
if (t instanceof StorageException) {
return restart();
} else {
return escalate();
}
}
});
@Override
public SupervisorStrategy supervisorStrategy() {
@ -261,7 +266,8 @@ public class FaultHandlingDocSample {
* when it has been terminated.
*/
void initStorage() {
storage = getContext().watch(getContext().actorOf(new Props(Storage.class), "storage"));
storage = getContext().watch(getContext().actorOf(
new Props(Storage.class), "storage"));
// Tell the counter, if any, to use the new storage
if (counter != null)
counter.tell(new UseStorage(storage), getSelf());
@ -272,14 +278,16 @@ public class FaultHandlingDocSample {
@Override
public void onReceive(Object msg) {
log.debug("received message {}", msg);
if (msg instanceof Entry && ((Entry) msg).key.equals(key) && counter == null) {
if (msg instanceof Entry && ((Entry) msg).key.equals(key) &&
counter == null) {
// Reply from Storage of the initial value, now we can create the Counter
final long value = ((Entry) msg).value;
counter = getContext().actorOf(new Props().withCreator(new UntypedActorFactory() {
public Actor create() {
return new Counter(key, value);
}
}));
counter = getContext().actorOf(new Props().withCreator(
new UntypedActorFactory() {
public Actor create() {
return new Counter(key, value);
}
}));
// Tell the counter to use current storage
counter.tell(new UseStorage(storage), getSelf());
// and send the buffered backlog to the counter
@ -299,7 +307,8 @@ public class FaultHandlingDocSample {
counter.tell(new UseStorage(null), getSelf());
// Try to re-establish storage after while
getContext().system().scheduler().scheduleOnce(
Duration.create(10, "seconds"), getSelf(), Reconnect, getContext().dispatcher()
Duration.create(10, "seconds"), getSelf(), Reconnect,
getContext().dispatcher()
);
} else if (msg.equals(Reconnect)) {
// Re-establish storage after the scheduled delay
@ -310,12 +319,13 @@ public class FaultHandlingDocSample {
}
void forwardOrPlaceInBacklog(Object msg) {
// We need the initial value from storage before we can start delegate to the counter.
// Before that we place the messages in a backlog, to be sent to the counter when
// it is initialized.
// We need the initial value from storage before we can start delegate to
// the counter. Before that we place the messages in a backlog, to be sent
// to the counter when it is initialized.
if (counter == null) {
if (backlog.size() >= MAX_BACKLOG)
throw new ServiceUnavailable("CounterService not available, lack of initial value");
throw new ServiceUnavailable("CounterService not available," +
" lack of initial value");
backlog.add(new SenderMsgPair(getSender(), msg));
} else {
counter.forward(msg, getContext());
@ -449,7 +459,8 @@ public class FaultHandlingDocSample {
} else if (msg instanceof Get) {
Get get = (Get) msg;
Long value = db.load(get.key);
getSender().tell(new Entry(get.key, value == null ? Long.valueOf(0L) : value), getSelf());
getSender().tell(new Entry(get.key, value == null ?
Long.valueOf(0L) : value), getSelf());
} else {
unhandled(msg);
}

View file

@ -28,13 +28,15 @@ public class ActivationTestBase {
Camel camel = CamelExtension.get(system);
// get a future reference to the activation of the endpoint of the Consumer Actor
Timeout timeout = new Timeout(Duration.create(10, SECONDS));
Future<ActorRef> activationFuture = camel.activationFutureFor(producer, timeout, system.dispatcher());
Future<ActorRef> activationFuture = camel.activationFutureFor(producer,
timeout, system.dispatcher());
//#CamelActivation
//#CamelDeactivation
// ..
system.stop(producer);
// get a future reference to the deactivation of the endpoint of the Consumer Actor
Future<ActorRef> deactivationFuture = camel.deactivationFutureFor(producer, timeout, system.dispatcher());
Future<ActorRef> deactivationFuture = camel.deactivationFutureFor(producer,
timeout, system.dispatcher());
//#CamelDeactivation
system.shutdown();
}

View file

@ -23,7 +23,8 @@ public class CamelExtensionTestBase {
ActorSystem system = ActorSystem.create("some-system");
Camel camel = CamelExtension.get(system);
CamelContext camelContext = camel.context();
// camelContext.addComponent("activemq", ActiveMQComponent.activeMQComponent("vm://localhost?broker.persistent=false"))
// camelContext.addComponent("activemq", ActiveMQComponent.activeMQComponent(
// "vm://localhost?broker.persistent=false"));
//#CamelExtensionAddComponent
system.shutdown();
}

View file

@ -8,7 +8,8 @@ import scala.concurrent.util.FiniteDuration;
import java.util.concurrent.TimeUnit;
public class Consumer4 extends UntypedConsumerActor {
private final static FiniteDuration timeout = Duration.create(500, TimeUnit.MILLISECONDS);
private final static FiniteDuration timeout =
Duration.create(500, TimeUnit.MILLISECONDS);
@Override
public FiniteDuration replyTimeout() {

View file

@ -12,12 +12,15 @@ import scala.Option;
public class ErrorThrowingConsumer extends UntypedConsumerActor{
private String uri;
private static Mapper<RouteDefinition, ProcessorDefinition<?>> mapper = new Mapper<RouteDefinition, ProcessorDefinition<?>>() {
public ProcessorDefinition<?> apply(RouteDefinition rd) {
// Catch any exception and handle it by returning the exception message as response
return rd.onException(Exception.class).handled(true).transform(Builder.exceptionMessage()).end();
}
};
private static Mapper<RouteDefinition, ProcessorDefinition<?>> mapper =
new Mapper<RouteDefinition, ProcessorDefinition<?>>() {
public ProcessorDefinition<?> apply(RouteDefinition rd) {
// Catch any exception and handle it by returning the exception message
// as response
return rd.onException(Exception.class).handled(true).
transform(Builder.exceptionMessage()).end();
}
};
public ErrorThrowingConsumer(String uri){
this.uri = uri;
@ -37,7 +40,8 @@ public class ErrorThrowingConsumer extends UntypedConsumerActor{
}
@Override
public Mapper<RouteDefinition, ProcessorDefinition<?>> getRouteDefinitionHandler() {
public Mapper<RouteDefinition,
ProcessorDefinition<?>> getRouteDefinitionHandler() {
return mapper;
}

View file

@ -39,7 +39,8 @@ public class ProducerTestBase {
ActorRef producer = system.actorOf(props,"jmsproducer");
Map<String,Object> headers = new HashMap<String, Object>();
headers.put(CamelMessage.MessageExchangeId(),"123");
producer.tell(new CamelMessage("<order amount=\"100\" currency=\"PLN\" itemId=\"12345\"/>",headers), null);
producer.tell(new CamelMessage("<order amount=\"100\" currency=\"PLN\" " +
"itemId=\"12345\"/>",headers), null);
//#Correlate
system.stop(producer);
system.shutdown();

View file

@ -6,7 +6,8 @@ public class HttpSample {
public static void main(String[] args) {
//#HttpExample
// Create the actors. this can be done in a Boot class so you can
// run the example in the MicroKernel. just add the below three lines to your boot class.
// run the example in the MicroKernel. Just add the three lines below
// to your boot class.
ActorSystem system = ActorSystem.create("some-system");
final ActorRef httpTransformer = system.actorOf(new Props(HttpTransformer.class));

View file

@ -11,7 +11,8 @@ public class HttpTransformer extends UntypedActor{
public void onReceive(Object message) {
if (message instanceof CamelMessage) {
CamelMessage camelMessage = (CamelMessage) message;
CamelMessage replacedMessage = camelMessage.mapBody(new Mapper<Object, String>(){
CamelMessage replacedMessage =
camelMessage.mapBody(new Mapper<Object, String>(){
@Override
public String apply(Object body) {
String text = new String((byte[])body);

View file

@ -19,7 +19,8 @@ public class Consumer3 extends UntypedConsumerActor{
public void onReceive(Object message) {
if (message instanceof CamelMessage) {
CamelMessage camelMessage = (CamelMessage) message;
transformer.forward(camelMessage.getBodyAs(String.class, getCamelContext()),getContext());
transformer.forward(camelMessage.getBodyAs(String.class, getCamelContext()),
getContext());
} else
unhandled(message);
}

View file

@ -9,7 +9,8 @@ public class CustomRouteBuilder extends RouteBuilder{
public void configure() throws Exception {
from("direct:welcome").process(new Processor(){
public void process(Exchange exchange) throws Exception {
exchange.getOut().setBody(String.format("Welcome %s",exchange.getIn().getBody()));
exchange.getOut().setBody(String.format("Welcome %s",
exchange.getIn().getBody()));
}
});
}

View file

@ -7,7 +7,8 @@ public class CustomRouteSample {
public static void main(String[] args) {
try {
//#CustomRouteExample
// the below lines can be added to a Boot class, so that you can run the example from a MicroKernel
// the below lines can be added to a Boot class, so that you can run the
// example from a MicroKernel
ActorSystem system = ActorSystem.create("some-system");
final ActorRef producer = system.actorOf(new Props(Producer1.class));
final ActorRef mediator = system.actorOf(new Props(new UntypedActorFactory() {

View file

@ -15,14 +15,16 @@ public class Transformer extends UntypedActor {
public void onReceive(Object message) {
if (message instanceof CamelMessage) {
// example: transform message body "foo" to "- foo -" and forward result to producer
// example: transform message body "foo" to "- foo -" and forward result
// to producer
CamelMessage camelMessage = (CamelMessage) message;
CamelMessage transformedMessage = camelMessage.mapBody(new Mapper<String, String>(){
@Override
public String apply(String body) {
return String.format("- %s -",body);
}
});
CamelMessage transformedMessage =
camelMessage.mapBody(new Mapper<String, String>(){
@Override
public String apply(String body) {
return String.format("- %s -",body);
}
});
producer.forward(transformedMessage, getContext());
} else
unhandled(message);

View file

@ -50,7 +50,8 @@ public class DispatcherDocTestBase {
@Before
public void setUp() {
system = ActorSystem.create("MySystem",
ConfigFactory.parseString(DispatcherDocSpec.config()).withFallback(AkkaSpec.testConf()));
ConfigFactory.parseString(
DispatcherDocSpec.config()).withFallback(AkkaSpec.testConf()));
}
@After
@ -79,7 +80,7 @@ public class DispatcherDocTestBase {
public void priorityDispatcher() throws Exception {
//#prio-dispatcher
// We create a new Actor that just prints out what it processes
// We create a new Actor that just prints out what it processes
ActorRef myActor = system.actorOf(
new Props().withCreator(new UntypedActorFactory() {
public UntypedActor create() {
@ -123,9 +124,11 @@ public class DispatcherDocTestBase {
}
}
static
//#prio-mailbox
public static class MyPrioMailbox extends UnboundedPriorityMailbox {
public MyPrioMailbox(ActorSystem.Settings settings, Config config) { // needed for reflective instantiation
public class MyPrioMailbox extends UnboundedPriorityMailbox {
// needed for reflective instantiation
public MyPrioMailbox(ActorSystem.Settings settings, Config config) {
// Create a new PriorityGenerator, lower prio means more important
super(new PriorityGenerator() {
@Override
@ -143,9 +146,10 @@ public class DispatcherDocTestBase {
}
}
//#prio-mailbox
static
//#mailbox-implementation-example
class MyUnboundedMailbox implements MailboxType {
public class MyUnboundedMailbox implements MailboxType {
// This constructor signature must exist, it will be called by Akka
public MyUnboundedMailbox(ActorSystem.Settings settings, Config config) {
@ -158,7 +162,9 @@ public class DispatcherDocTestBase {
private final Queue<Envelope> queue = new ConcurrentLinkedQueue<Envelope>();
// these must be implemented; queue used as example
public void enqueue(ActorRef receiver, Envelope handle) { queue.offer(handle); }
public void enqueue(ActorRef receiver, Envelope handle) {
queue.offer(handle);
}
public Envelope dequeue() { return queue.poll(); }
public int numberOfMessages() { return queue.size(); }
public boolean hasMessages() { return !queue.isEmpty(); }

View file

@ -76,8 +76,8 @@ public class LoggingDocTestBase {
@Override
public void preRestart(Throwable reason, Option<Object> message) {
log.error(reason, "Restarting due to [{}] when processing [{}]", reason.getMessage(),
message.isDefined() ? message.get() : "");
log.error(reason, "Restarting due to [{}] when processing [{}]",
reason.getMessage(), message.isDefined() ? message.get() : "");
}
public void onReceive(Object message) {
@ -109,8 +109,9 @@ public class LoggingDocTestBase {
}
//#my-event-listener
static
//#deadletter-actor
public static class DeadLetterActor extends UntypedActor {
public class DeadLetterActor extends UntypedActor {
public void onReceive(Object message) {
if (message instanceof DeadLetter) {
System.out.println(message);

View file

@ -13,8 +13,9 @@ import org.junit.Test;
public class ExtensionDocTestBase {
static
//#extension
public static class CountExtensionImpl implements Extension {
public class CountExtensionImpl implements Extension {
//Since this Extension is a shared instance
// per ActorSystem we need to be threadsafe
private final AtomicLong counter = new AtomicLong(0);
@ -27,8 +28,10 @@ public class ExtensionDocTestBase {
//#extension
static
//#extensionid
public static class CountExtension extends AbstractExtensionId<CountExtensionImpl> implements ExtensionIdProvider {
public class CountExtension extends AbstractExtensionId<CountExtensionImpl>
implements ExtensionIdProvider {
//This will be the identifier of our CountExtension
public final static CountExtension CountExtensionProvider = new CountExtension();
@ -49,10 +52,12 @@ public class ExtensionDocTestBase {
//#extensionid
static
//#extension-usage-actor
public static class MyActor extends UntypedActor {
public class MyActor extends UntypedActor {
public void onReceive(Object msg) {
// typically you would use static import of CountExtension.CountExtensionProvider field
// typically you would use static import of the
// CountExtension.CountExtensionProvider field
CountExtension.CountExtensionProvider.get(getContext().system()).increment();
}
}
@ -64,7 +69,8 @@ public class ExtensionDocTestBase {
final ActorSystem system = null;
try {
//#extension-usage
// typically you would use static import of CountExtension.CountExtensionProvider field
// typically you would use static import of the
// CountExtension.CountExtensionProvider field
CountExtension.CountExtensionProvider.get(system).increment();
//#extension-usage
} catch (Exception e) {

View file

@ -20,15 +20,17 @@ import org.junit.Test;
public class SettingsExtensionDocTestBase {
static
//#extension
public static class SettingsImpl implements Extension {
public class SettingsImpl implements Extension {
public final String DB_URI;
public final Duration CIRCUIT_BREAKER_TIMEOUT;
public SettingsImpl(Config config) {
DB_URI = config.getString("myapp.db.uri");
CIRCUIT_BREAKER_TIMEOUT = Duration.create(config.getMilliseconds("myapp.circuit-breaker.timeout"),
CIRCUIT_BREAKER_TIMEOUT =
Duration.create(config.getMilliseconds("myapp.circuit-breaker.timeout"),
TimeUnit.MILLISECONDS);
}
@ -36,8 +38,10 @@ public class SettingsExtensionDocTestBase {
//#extension
static
//#extensionid
public static class Settings extends AbstractExtensionId<SettingsImpl> implements ExtensionIdProvider {
public class Settings extends AbstractExtensionId<SettingsImpl>
implements ExtensionIdProvider {
public final static Settings SettingsProvider = new Settings();
public Settings lookup() {
@ -51,13 +55,16 @@ public class SettingsExtensionDocTestBase {
//#extensionid
static
//#extension-usage-actor
public static class MyActor extends UntypedActor {
// typically you would use static import of CountExtension.CountExtensionProvider field
final SettingsImpl settings = Settings.SettingsProvider.get(getContext().system());
Connection connection = connect(settings.DB_URI, settings.CIRCUIT_BREAKER_TIMEOUT);
public class MyActor extends UntypedActor {
// typically you would use static import of the Settings.SettingsProvider field
final SettingsImpl settings =
Settings.SettingsProvider.get(getContext().system());
Connection connection =
connect(settings.DB_URI, settings.CIRCUIT_BREAKER_TIMEOUT);
//#extension-usage-actor
//#extension-usage-actor
public Connection connect(String dbUri, Duration circuitBreakerTimeout) {
return new Connection();
@ -65,8 +72,9 @@ public class SettingsExtensionDocTestBase {
public void onReceive(Object msg) {
}
//#extension-usage-actor
}
//#extension-usage-actor
public static class Connection {
}
@ -76,7 +84,7 @@ public class SettingsExtensionDocTestBase {
final ActorSystem system = null;
try {
//#extension-usage
// typically you would use static import of CountExtension.CountExtensionProvider field
// typically you would use static import of the Settings.SettingsProvider field
String dbUri = Settings.SettingsProvider.get(system).DB_URI;
//#extension-usage
} catch (Exception e) {

View file

@ -9,7 +9,6 @@ import scala.concurrent.ExecutionContext;
import scala.concurrent.Future;
import scala.concurrent.Await;
import akka.util.Timeout;
//#imports1
//#imports2
@ -18,39 +17,32 @@ import akka.japi.Function;
import java.util.concurrent.Callable;
import static akka.dispatch.Futures.future;
import static java.util.concurrent.TimeUnit.SECONDS;
//#imports2
//#imports3
import static akka.dispatch.Futures.sequence;
//#imports3
//#imports4
import static akka.dispatch.Futures.traverse;
//#imports4
//#imports5
import akka.japi.Function2;
import static akka.dispatch.Futures.fold;
//#imports5
//#imports6
import static akka.dispatch.Futures.reduce;
//#imports6
//#imports7
import scala.concurrent.ExecutionContext;
import scala.concurrent.ExecutionContext$;
//#imports7
//#imports8
import static akka.pattern.Patterns.after;
//#imports8
import java.util.ArrayList;
@ -96,7 +88,7 @@ public class FutureDocTestBase {
//Use ec with your Futures
Future<String> f1 = Futures.successful("foo");
// Then you shut the ExecutorService down somewhere at the end of your program/application.
// Then you shut down the ExecutorService at the end of your application.
yourExecutorServiceGoesHere.shutdown();
//#diy-execution-context
}
@ -236,14 +228,15 @@ public class FutureDocTestBase {
Future<Iterable<Integer>> futureListOfInts = sequence(listOfFutureInts, ec);
// Find the sum of the odd numbers
Future<Long> futureSum = futureListOfInts.map(new Mapper<Iterable<Integer>, Long>() {
public Long apply(Iterable<Integer> ints) {
long sum = 0;
for (Integer i : ints)
sum += i;
return sum;
}
}, ec);
Future<Long> futureSum = futureListOfInts.map(
new Mapper<Iterable<Integer>, Long>() {
public Long apply(Iterable<Integer> ints) {
long sum = 0;
for (Integer i : ints)
sum += i;
return sum;
}
}, ec);
long result = Await.result(futureSum, Duration.create(1, SECONDS));
//#sequence
@ -257,15 +250,16 @@ public class FutureDocTestBase {
//Just a sequence of Strings
Iterable<String> listStrings = Arrays.asList("a", "b", "c");
Future<Iterable<String>> futureResult = traverse(listStrings, new Function<String, Future<String>>() {
public Future<String> apply(final String r) {
return future(new Callable<String>() {
public String call() {
return r.toUpperCase();
}
}, ec);
}
}, ec);
Future<Iterable<String>> futureResult = traverse(listStrings,
new Function<String, Future<String>>() {
public Future<String> apply(final String r) {
return future(new Callable<String>() {
public String call() {
return r.toUpperCase();
}
}, ec);
}
}, ec);
//Returns the sequence of strings as upper case
Iterable<String> result = Await.result(futureResult, Duration.create(1, SECONDS));
@ -286,11 +280,12 @@ public class FutureDocTestBase {
Iterable<Future<String>> futures = source;
//Start value is the empty string
Future<String> resultFuture = fold("", futures, new Function2<String, String, String>() {
public String apply(String r, String t) {
return r + t; //Just concatenate
}
}, ec);
Future<String> resultFuture = fold("", futures,
new Function2<String, String, String>() {
public String apply(String r, String t) {
return r + t; //Just concatenate
}
}, ec);
String result = Await.result(resultFuture, Duration.create(1, SECONDS));
//#fold
@ -308,11 +303,12 @@ public class FutureDocTestBase {
//A sequence of Futures, in this case Strings
Iterable<Future<String>> futures = source;
Future<Object> resultFuture = reduce(futures, new Function2<Object, String, Object>() {
public Object apply(Object r, String t) {
return r + t; //Just concatenate
}
}, ec);
Future<Object> resultFuture = reduce(futures,
new Function2<Object, String, Object>() {
public Object apply(Object r, String t) {
return r + t; //Just concatenate
}
}, ec);
Object result = Await.result(resultFuture, Duration.create(1, SECONDS));
//#reduce
@ -327,11 +323,13 @@ public class FutureDocTestBase {
Future<String> future = Futures.successful("Yay!");
//#successful
//#failed
Future<String> otherFuture = Futures.failed(new IllegalArgumentException("Bang!"));
Future<String> otherFuture = Futures.failed(
new IllegalArgumentException("Bang!"));
//#failed
Object result = Await.result(future, Duration.create(1, SECONDS));
assertEquals("Yay!", result);
Throwable result2 = Await.result(otherFuture.failed(), Duration.create(1, SECONDS));
Throwable result2 = Await.result(otherFuture.failed(),
Duration.create(1, SECONDS));
assertEquals("Bang!", result2.getMessage());
}
@ -340,17 +338,19 @@ public class FutureDocTestBase {
//#filter
final ExecutionContext ec = system.dispatcher();
Future<Integer> future1 = Futures.successful(4);
Future<Integer> successfulFilter = future1.filter(Filter.filterOf(new Function<Integer, Boolean>() {
public Boolean apply(Integer i) {
return i % 2 == 0;
}
}), ec);
Future<Integer> successfulFilter = future1.filter(Filter.filterOf(
new Function<Integer, Boolean>() {
public Boolean apply(Integer i) {
return i % 2 == 0;
}
}), ec);
Future<Integer> failedFilter = future1.filter(Filter.filterOf(new Function<Integer, Boolean>() {
public Boolean apply(Integer i) {
return i % 2 != 0;
}
}), ec);
Future<Integer> failedFilter = future1.filter(Filter.filterOf(
new Function<Integer, Boolean>() {
public Boolean apply(Integer i) {
return i % 2 != 0;
}
}), ec);
//When filter fails, the returned Future will be failed with a scala.MatchError
//#filter
}
@ -367,12 +367,13 @@ public class FutureDocTestBase {
public void useAndThen() {
//#and-then
final ExecutionContext ec = system.dispatcher();
Future<String> future1 = Futures.successful("value").andThen(new OnComplete<String>() {
Future<String> future1 = Futures.successful("value").andThen(
new OnComplete<String>() {
public void onComplete(Throwable failure, String result) {
if (failure != null)
sendToIssueTracker(failure);
if (failure != null)
sendToIssueTracker(failure);
}
}, ec).andThen(new OnComplete<String>() {
}, ec).andThen(new OnComplete<String>() {
public void onComplete(Throwable failure, String result) {
if (result != null)
sendToTheInternetz(result);
@ -489,11 +490,12 @@ public class FutureDocTestBase {
final ExecutionContext ec = system.dispatcher();
Future<String> future1 = Futures.successful("foo");
Future<String> future2 = Futures.successful("bar");
Future<String> future3 = future1.zip(future2).map(new Mapper<scala.Tuple2<String, String>, String>() {
public String apply(scala.Tuple2<String, String> zipped) {
return zipped._1() + " " + zipped._2();
}
}, ec);
Future<String> future3 = future1.zip(future2).map(
new Mapper<scala.Tuple2<String, String>, String>() {
public String apply(scala.Tuple2<String, String> zipped) {
return zipped._1() + " " + zipped._2();
}
}, ec);
String result = Await.result(future3, Duration.create(1, SECONDS));
assertEquals("foo bar", result);
@ -505,7 +507,8 @@ public class FutureDocTestBase {
Future<String> future1 = Futures.failed(new IllegalStateException("OHNOES1"));
Future<String> future2 = Futures.failed(new IllegalStateException("OHNOES2"));
Future<String> future3 = Futures.successful("bar");
Future<String> future4 = future1.fallbackTo(future2).fallbackTo(future3); // Will have "bar" in this case
// Will have "bar" in this case
Future<String> future4 = future1.fallbackTo(future2).fallbackTo(future3);
String result = Await.result(future4, Duration.create(1, SECONDS));
assertEquals("bar", result);
//#fallback-to

View file

@ -39,9 +39,9 @@ public class ConsistentHashingRouterDocTestBase {
system.shutdown();
}
static
//#cache-actor
public static class Cache extends UntypedActor {
public class Cache extends UntypedActor {
Map<String, String> cache = new HashMap<String, String>();
public void onReceive(Object msg) {
@ -62,14 +62,20 @@ public class ConsistentHashingRouterDocTestBase {
}
}
public static final class Evict implements Serializable {
//#cache-actor
static
//#cache-actor
public final class Evict implements Serializable {
public final String key;
public Evict(String key) {
this.key = key;
}
}
public static final class Get implements Serializable, ConsistentHashable {
//#cache-actor
static
//#cache-actor
public final class Get implements Serializable, ConsistentHashable {
public final String key;
public Get(String key) {
this.key = key;
@ -79,7 +85,10 @@ public class ConsistentHashingRouterDocTestBase {
}
}
public static final class Entry implements Serializable {
//#cache-actor
static
//#cache-actor
public final class Entry implements Serializable {
public final String key;
public final String value;
public Entry(String key, String value) {
@ -88,7 +97,10 @@ public class ConsistentHashingRouterDocTestBase {
}
}
public static final String NOT_FOUND = "NOT_FOUND";
//#cache-actor
static
//#cache-actor
public final String NOT_FOUND = "NOT_FOUND";
//#cache-actor

View file

@ -57,15 +57,18 @@ public class CustomRouterDocTestBase {
public void demonstrateDispatchers() {
//#dispatchers
final ActorRef router = system.actorOf(new Props(MyActor.class)
.withRouter(new RoundRobinRouter(5).withDispatcher("head")) // head router runs on "head" dispatcher
.withDispatcher("workers")); // MyActor workers run on "workers" dispatcher
// head router will run on "head" dispatcher
.withRouter(new RoundRobinRouter(5).withDispatcher("head"))
// MyActor workers will run on "workers" dispatcher
.withDispatcher("workers"));
//#dispatchers
}
@Test
public void demonstrateSupervisor() {
//#supervision
final SupervisorStrategy strategy = new OneForOneStrategy(5, Duration.parse("1 minute"),
final SupervisorStrategy strategy =
new OneForOneStrategy(5, Duration.parse("1 minute"),
new Class<?>[] { Exception.class });
final ActorRef router = system.actorOf(new Props(MyActor.class)
.withRouter(new RoundRobinRouter(5).withSupervisorStrategy(strategy)));
@ -75,15 +78,18 @@ public class CustomRouterDocTestBase {
//#crTest
@Test
public void countVotesAsIntendedNotAsInFlorida() throws Exception {
ActorRef routedActor = system.actorOf(new Props().withRouter(new VoteCountRouter()));
ActorRef routedActor = system.actorOf(
new Props().withRouter(new VoteCountRouter()));
routedActor.tell(DemocratVote, null);
routedActor.tell(DemocratVote, null);
routedActor.tell(RepublicanVote, null);
routedActor.tell(DemocratVote, null);
routedActor.tell(RepublicanVote, null);
Timeout timeout = new Timeout(Duration.create(1, "seconds"));
Future<Object> democratsResult = ask(routedActor, DemocratCountResult, timeout);
Future<Object> republicansResult = ask(routedActor, RepublicanCountResult, timeout);
Future<Object> democratsResult =
ask(routedActor, DemocratCountResult, timeout);
Future<Object> republicansResult =
ask(routedActor, RepublicanCountResult, timeout);
assertEquals(3, Await.result(democratsResult, timeout.duration()));
assertEquals(2, Await.result(republicansResult, timeout.duration()));
@ -98,9 +104,11 @@ public class CustomRouterDocTestBase {
}
//#crMessages
//#CustomRouter
static
//#CustomRouter
//#crActors
public static class DemocratActor extends UntypedActor {
public class DemocratActor extends UntypedActor {
int counter = 0;
public void onReceive(Object msg) {
@ -117,7 +125,12 @@ public class CustomRouterDocTestBase {
}
}
public static class RepublicanActor extends UntypedActor {
//#crActors
//#CustomRouter
static
//#CustomRouter
//#crActors
public class RepublicanActor extends UntypedActor {
int counter = 0;
public void onReceive(Object msg) {
@ -135,9 +148,11 @@ public class CustomRouterDocTestBase {
}
//#crActors
//#CustomRouter
static
//#CustomRouter
//#crRouter
public static class VoteCountRouter extends CustomRouterConfig {
public class VoteCountRouter extends CustomRouterConfig {
@Override public String routerDispatcher() {
return Dispatchers.DefaultDispatcherId();
@ -150,9 +165,12 @@ public class CustomRouterDocTestBase {
//#crRoute
@Override
public CustomRoute createCustomRoute(RouteeProvider routeeProvider) {
final ActorRef democratActor = routeeProvider.context().actorOf(new Props(DemocratActor.class), "d");
final ActorRef republicanActor = routeeProvider.context().actorOf(new Props(RepublicanActor.class), "r");
List<ActorRef> routees = Arrays.asList(new ActorRef[] { democratActor, republicanActor });
final ActorRef democratActor =
routeeProvider.context().actorOf(new Props(DemocratActor.class), "d");
final ActorRef republicanActor =
routeeProvider.context().actorOf(new Props(RepublicanActor.class), "r");
List<ActorRef> routees =
Arrays.asList(new ActorRef[] { democratActor, republicanActor });
//#crRegisterRoutees
routeeProvider.registerRoutees(routees);
@ -165,10 +183,12 @@ public class CustomRouterDocTestBase {
switch ((Message) msg) {
case DemocratVote:
case DemocratCountResult:
return Arrays.asList(new Destination[] { new Destination(sender, democratActor) });
return Arrays.asList(
new Destination[] { new Destination(sender, democratActor) });
case RepublicanVote:
case RepublicanCountResult:
return Arrays.asList(new Destination[] { new Destination(sender, republicanActor) });
return Arrays.asList(
new Destination[] { new Destination(sender, republicanActor) });
default:
throw new IllegalArgumentException("Unknown message: " + msg);
}
@ -182,5 +202,4 @@ public class CustomRouterDocTestBase {
//#crRouter
//#CustomRouter
}

View file

@ -22,14 +22,16 @@ public class ParentActor extends UntypedActor {
if (msg.equals("rrr")) {
//#roundRobinRouter
ActorRef roundRobinRouter = getContext().actorOf(
new Props(PrintlnActor.class).withRouter(new RoundRobinRouter(5)), "router");
new Props(PrintlnActor.class).withRouter(new RoundRobinRouter(5)),
"router");
for (int i = 1; i <= 10; i++) {
roundRobinRouter.tell(i, getSelf());
}
//#roundRobinRouter
} else if (msg.equals("rr")) {
//#randomRouter
ActorRef randomRouter = getContext().actorOf(new Props(PrintlnActor.class).withRouter(new RandomRouter(5)),
ActorRef randomRouter = getContext().actorOf(
new Props(PrintlnActor.class).withRouter(new RandomRouter(5)),
"router");
for (int i = 1; i <= 10; i++) {
randomRouter.tell(i, getSelf());
@ -38,28 +40,32 @@ public class ParentActor extends UntypedActor {
} else if (msg.equals("smr")) {
//#smallestMailboxRouter
ActorRef smallestMailboxRouter = getContext().actorOf(
new Props(PrintlnActor.class).withRouter(new SmallestMailboxRouter(5)), "router");
new Props(PrintlnActor.class).withRouter(new SmallestMailboxRouter(5)),
"router");
for (int i = 1; i <= 10; i++) {
smallestMailboxRouter.tell(i, getSelf());
}
//#smallestMailboxRouter
} else if (msg.equals("br")) {
//#broadcastRouter
ActorRef broadcastRouter = getContext().actorOf(new Props(PrintlnActor.class).withRouter(new BroadcastRouter(5)),
"router");
ActorRef broadcastRouter = getContext().actorOf(
new Props(PrintlnActor.class).withRouter(new BroadcastRouter(5)), "router");
broadcastRouter.tell("this is a broadcast message", getSelf());
//#broadcastRouter
} else if (msg.equals("sgfcr")) {
//#scatterGatherFirstCompletedRouter
ActorRef scatterGatherFirstCompletedRouter = getContext().actorOf(
new Props(FibonacciActor.class).withRouter(new ScatterGatherFirstCompletedRouter(5, Duration
.create(2, "seconds"))), "router");
new Props(FibonacciActor.class).withRouter(
new ScatterGatherFirstCompletedRouter(5, Duration.create(2, "seconds"))),
"router");
Timeout timeout = new Timeout(Duration.create(5, "seconds"));
Future<Object> futureResult = akka.pattern.Patterns.ask(scatterGatherFirstCompletedRouter,
new FibonacciActor.FibonacciNumber(10), timeout);
Future<Object> futureResult = akka.pattern.Patterns.ask(
scatterGatherFirstCompletedRouter, new FibonacciActor.FibonacciNumber(10),
timeout);
int result = (Integer) Await.result(futureResult, timeout.duration());
//#scatterGatherFirstCompletedRouter
System.out.println(String.format("The result of calculating Fibonacci for 10 is %d", result));
System.out.println(
String.format("The result of calculating Fibonacci for 10 is %d", result));
} else {
unhandled(msg);
}

View file

@ -8,7 +8,8 @@ import akka.actor.UntypedActor;
//#printlnActor
public class PrintlnActor extends UntypedActor {
public void onReceive(Object msg) {
System.out.println(String.format("Received message '%s' in actor %s", msg, getSelf().path().name()));
System.out.println(String.format("Received message '%s' in actor %s",
msg, getSelf().path().name()));
}
}

View file

@ -17,7 +17,8 @@ public class RouterViaConfigExample {
public void onReceive(Object msg) {
if (msg instanceof Message) {
Message message = (Message) msg;
System.out.println(String.format("Received %s in router %s", message.getNbr(), getSelf().path().name()));
System.out.println(String.format("Received %s in router %s",
message.getNbr(), getSelf().path().name()));
} else {
unhandled(msg);
}
@ -42,14 +43,16 @@ public class RouterViaConfigExample {
+ " router = round-robin\n" + " nr-of-instances = 5\n" + " }\n" + "}\n");
ActorSystem system = ActorSystem.create("Example", config);
//#configurableRouting
ActorRef router = system.actorOf(new Props(ExampleActor.class).withRouter(new FromConfig()), "router");
ActorRef router = system.actorOf(
new Props(ExampleActor.class).withRouter(new FromConfig()), "router");
//#configurableRouting
for (int i = 1; i <= 10; i++) {
router.tell(new ExampleActor.Message(i), null);
}
//#configurableRoutingWithResizer
ActorRef router2 = system.actorOf(new Props(ExampleActor.class).withRouter(new FromConfig()), "router2");
ActorRef router2 = system.actorOf(
new Props(ExampleActor.class).withRouter(new FromConfig()), "router2");
//#configurableRoutingWithResizer
for (int i = 1; i <= 10; i++) {
router2.tell(new ExampleActor.Message(i), null);

View file

@ -20,7 +20,8 @@ public class RouterViaProgramExample {
public void onReceive(Object msg) {
if (msg instanceof Message) {
Message message = (Message) msg;
System.out.println(String.format("Received %s in router %s", message.getNbr(), getSelf().path().name()));
System.out.println(String.format("Received %s in router %s",
message.getNbr(), getSelf().path().name()));
} else {
unhandled(msg);
}
@ -44,7 +45,8 @@ public class RouterViaProgramExample {
ActorSystem system = ActorSystem.create("RPE");
//#programmaticRoutingNrOfInstances
int nrOfInstances = 5;
ActorRef router1 = system.actorOf(new Props(ExampleActor.class).withRouter(new RoundRobinRouter(nrOfInstances)));
ActorRef router1 = system.actorOf(
new Props(ExampleActor.class).withRouter(new RoundRobinRouter(nrOfInstances)));
//#programmaticRoutingNrOfInstances
for (int i = 1; i <= 6; i++) {
router1.tell(new ExampleActor.Message(i), null);
@ -54,8 +56,10 @@ public class RouterViaProgramExample {
ActorRef actor1 = system.actorOf(new Props(ExampleActor.class));
ActorRef actor2 = system.actorOf(new Props(ExampleActor.class));
ActorRef actor3 = system.actorOf(new Props(ExampleActor.class));
Iterable<ActorRef> routees = Arrays.asList(new ActorRef[] { actor1, actor2, actor3 });
ActorRef router2 = system.actorOf(new Props().withRouter(RoundRobinRouter.create(routees)));
Iterable<ActorRef> routees = Arrays.asList(
new ActorRef[] { actor1, actor2, actor3 });
ActorRef router2 = system.actorOf(
new Props().withRouter(RoundRobinRouter.create(routees)));
//#programmaticRoutingRoutees
for (int i = 1; i <= 6; i++) {
router2.tell(new ExampleActor.Message(i), null);
@ -65,7 +69,8 @@ public class RouterViaProgramExample {
int lowerBound = 2;
int upperBound = 15;
DefaultResizer resizer = new DefaultResizer(lowerBound, upperBound);
ActorRef router3 = system.actorOf(new Props(ExampleActor.class).withRouter(new RoundRobinRouter(nrOfInstances)));
ActorRef router3 = system.actorOf(
new Props(ExampleActor.class).withRouter(new RoundRobinRouter(nrOfInstances)));
//#programmaticRoutingWithResizer
for (int i = 1; i <= 6; i++) {
router3.tell(new ExampleActor.Message(i), null);

View file

@ -46,7 +46,8 @@ public class RemoteDeploymentDocTestBase {
addr = AddressFromURIString.parse("akka://sys@host:1234"); // the same
//#make-address
//#deploy
ActorRef ref = system.actorOf(new Props(SampleActor.class).withDeploy(new Deploy(new RemoteScope(addr))));
ActorRef ref = system.actorOf(new Props(SampleActor.class).withDeploy(
new Deploy(new RemoteScope(addr))));
//#deploy
assert ref.path().address().equals(addr);
}

View file

@ -13,118 +13,124 @@ import akka.serialization.*;
//#imports
public class SerializationDocTestBase {
static
//#my-own-serializer
public static class MyOwnSerializer extends JSerializer {
public class MyOwnSerializer extends JSerializer {
// This is whether "fromBinary" requires a "clazz" or not
@Override public boolean includeManifest() {
return false;
}
// Pick a unique identifier for your Serializer,
// you've got a couple of billions to choose from,
// 0 - 16 is reserved by Akka itself
@Override public int identifier() {
return 1234567;
}
// "toBinary" serializes the given object to an Array of Bytes
@Override public byte[] toBinary(Object obj) {
// Put the code that serializes the object here
//#...
return new byte[0];
//#...
}
// "fromBinary" deserializes the given array,
// using the type hint (if any, see "includeManifest" above)
@Override public Object fromBinaryJava(byte[] bytes,
Class<?> clazz) {
// Put your code that deserializes here
//#...
return null;
//#...
}
// This is whether "fromBinary" requires a "clazz" or not
@Override public boolean includeManifest() {
return false;
}
// Pick a unique identifier for your Serializer,
// you've got a couple of billions to choose from,
// 0 - 16 is reserved by Akka itself
@Override public int identifier() {
return 1234567;
}
// "toBinary" serializes the given object to an Array of Bytes
@Override public byte[] toBinary(Object obj) {
// Put the code that serializes the object here
//#...
return new byte[0];
//#...
}
// "fromBinary" deserializes the given array,
// using the type hint (if any, see "includeManifest" above)
@Override public Object fromBinaryJava(byte[] bytes,
Class<?> clazz) {
// Put your code that deserializes here
//#...
return null;
//#...
}
}
//#my-own-serializer
@Test public void serializeActorRefs() {
final ActorSystem theActorSystem =
ActorSystem.create("whatever");
final ActorRef theActorRef =
theActorSystem.deadLetters(); // Of course this should be you
@Test public void serializeActorRefs() {
final ActorSystem theActorSystem =
ActorSystem.create("whatever");
final ActorRef theActorRef =
theActorSystem.deadLetters(); // Of course this should be you
//#actorref-serializer
// Serialize
// (beneath toBinary)
final Address transportAddress =
Serialization.currentTransportAddress().value();
String identifier;
//#actorref-serializer
// Serialize
// (beneath toBinary)
final Address transportAddress =
Serialization.currentTransportAddress().value();
String identifier;
// If there is no transportAddress,
// it means that either this Serializer isn't called
// within a piece of code that sets it,
// so either you need to supply your own,
// or simply use the local path.
if (transportAddress == null) identifier = theActorRef.path().toString();
else identifier = theActorRef.path().toStringWithAddress(transportAddress);
// Then just serialize the identifier however you like
// If there is no transportAddress,
// it means that either this Serializer isn't called
// within a piece of code that sets it,
// so either you need to supply your own,
// or simply use the local path.
if (transportAddress == null) identifier = theActorRef.path().toString();
else identifier = theActorRef.path().toStringWithAddress(transportAddress);
// Then just serialize the identifier however you like
// Deserialize
// (beneath fromBinary)
final ActorRef deserializedActorRef = theActorSystem.actorFor(identifier);
// Then just use the ActorRef
//#actorref-serializer
theActorSystem.shutdown();
}
//#external-address
public static class ExternalAddressExt implements Extension {
private final ExtendedActorSystem system;
// Deserialize
// (beneath fromBinary)
final ActorRef deserializedActorRef = theActorSystem.actorFor(identifier);
// Then just use the ActorRef
//#actorref-serializer
theActorSystem.shutdown();
}
public ExternalAddressExt(ExtendedActorSystem system) {
this.system = system;
}
static
//#external-address
public class ExternalAddressExt implements Extension {
private final ExtendedActorSystem system;
public Address getAddressFor(Address remoteAddress) {
final scala.Option<Address> optAddr = system.provider()
.getExternalAddressFor(remoteAddress);
if (optAddr.isDefined()) {
return optAddr.get();
} else {
throw new UnsupportedOperationException(
"cannot send to remote address " + remoteAddress);
}
}
public ExternalAddressExt(ExtendedActorSystem system) {
this.system = system;
}
public static class ExternalAddress extends
AbstractExtensionId<ExternalAddressExt> implements ExtensionIdProvider {
public static final ExternalAddress ID = new ExternalAddress();
public ExternalAddress lookup() {
return ID;
}
public ExternalAddressExt createExtension(ExtendedActorSystem system) {
return new ExternalAddressExt(system);
public Address getAddressFor(Address remoteAddress) {
final scala.Option<Address> optAddr = system.provider()
.getExternalAddressFor(remoteAddress);
if (optAddr.isDefined()) {
return optAddr.get();
} else {
throw new UnsupportedOperationException(
"cannot send to remote address " + remoteAddress);
}
}
//#external-address
}
public void demonstrateExternalAddress() {
// this is not meant to be run, only to be compiled
final ActorSystem system = ActorSystem.create();
final Address remoteAddr = new Address("", "");
// #external-address
final Address addr = ExternalAddress.ID.get(system).getAddressFor(remoteAddr);
// #external-address
//#external-address
static
//#external-address
public class ExternalAddress extends
AbstractExtensionId<ExternalAddressExt> implements ExtensionIdProvider {
public static final ExternalAddress ID = new ExternalAddress();
public ExternalAddress lookup() {
return ID;
}
public ExternalAddressExt createExtension(ExtendedActorSystem system) {
return new ExternalAddressExt(system);
}
}
//#external-address
public void demonstrateExternalAddress() {
// this is not meant to be run, only to be compiled
final ActorSystem system = ActorSystem.create();
final Address remoteAddr = new Address("", "");
// #external-address
final Address addr = ExternalAddress.ID.get(system).getAddressFor(remoteAddr);
// #external-address
}
static
//#external-address-default
public static class DefaultAddressExt implements Extension {
public class DefaultAddressExt implements Extension {
private final ExtendedActorSystem system;
public DefaultAddressExt(ExtendedActorSystem system) {
@ -141,7 +147,10 @@ public class SerializationDocTestBase {
}
}
public static class DefaultAddress extends
//#external-address-default
static
//#external-address-default
public class DefaultAddress extends
AbstractExtensionId<DefaultAddressExt> implements ExtensionIdProvider {
public static final DefaultAddress ID = new DefaultAddress();

View file

@ -20,7 +20,8 @@ public class CoordinatedCounter extends UntypedActor {
if (message instanceof Increment) {
Increment increment = (Increment) message;
if (increment.hasFriend()) {
increment.getFriend().tell(coordinated.coordinate(new Increment()), getSelf());
increment.getFriend().tell(
coordinated.coordinate(new Increment()), getSelf());
}
coordinated.atomic(new Runnable() {
public void run() {

View file

@ -30,7 +30,8 @@ public class TransactorDocTest {
counter1.tell(new Coordinated(new Increment(counter2), timeout), null);
Integer count = (Integer) Await.result(ask(counter1, "GetCount", timeout), timeout.duration());
Integer count = (Integer) Await.result(
ask(counter1, "GetCount", timeout), timeout.duration());
//#coordinated-example
assertEquals(count, new Integer(1));

View file

@ -3,32 +3,28 @@
*/
package docs.zeromq;
//#pub-socket
//#import-pub-socket
import akka.zeromq.Bind;
import akka.zeromq.ZeroMQExtension;
//#pub-socket
//#sub-socket
//#import-pub-socket
//#import-sub-socket
import akka.zeromq.Connect;
import akka.zeromq.Listener;
import akka.zeromq.Subscribe;
//#sub-socket
//#unsub-topic-socket
//#import-sub-socket
//#import-unsub-topic-socket
import akka.zeromq.Unsubscribe;
//#unsub-topic-socket
//#pub-topic
//#import-unsub-topic-socket
//#import-pub-topic
import akka.zeromq.Frame;
import akka.zeromq.ZMQMessage;
//#pub-topic
//#import-pub-topic
import akka.zeromq.HighWatermark;
import akka.zeromq.SocketOption;
import akka.zeromq.ZeroMQVersion;
//#health
//#import-health
import akka.actor.ActorRef;
import akka.actor.UntypedActor;
import akka.actor.Props;
@ -39,7 +35,7 @@ import akka.serialization.SerializationExtension;
import akka.serialization.Serialization;
import java.io.Serializable;
import java.lang.management.ManagementFactory;
//#health
//#import-health
import com.typesafe.config.ConfigFactory;
@ -77,18 +73,21 @@ public class ZeromqDocTestBase {
Assume.assumeTrue(checkZeroMQInstallation());
//#pub-socket
ActorRef pubSocket = ZeroMQExtension.get(system).newPubSocket(new Bind("tcp://127.0.0.1:1233"));
ActorRef pubSocket = ZeroMQExtension.get(system).newPubSocket(
new Bind("tcp://127.0.0.1:1233"));
//#pub-socket
//#sub-socket
ActorRef listener = system.actorOf(new Props(ListenerActor.class));
ActorRef subSocket = ZeroMQExtension.get(system).newSubSocket(new Connect("tcp://127.0.0.1:1233"),
new Listener(listener), Subscribe.all());
ActorRef subSocket = ZeroMQExtension.get(system).newSubSocket(
new Connect("tcp://127.0.0.1:1233"),
new Listener(listener), Subscribe.all());
//#sub-socket
//#sub-topic-socket
ActorRef subTopicSocket = ZeroMQExtension.get(system).newSubSocket(new Connect("tcp://127.0.0.1:1233"),
new Listener(listener), new Subscribe("foo.bar"));
ActorRef subTopicSocket = ZeroMQExtension.get(system).newSubSocket(
new Connect("tcp://127.0.0.1:1233"),
new Listener(listener), new Subscribe("foo.bar"));
//#sub-topic-socket
//#unsub-topic-socket
@ -102,7 +101,8 @@ public class ZeromqDocTestBase {
//#high-watermark
ActorRef highWatermarkSocket = ZeroMQExtension.get(system).newRouterSocket(
new SocketOption[] { new Listener(listener), new Bind("tcp://127.0.0.1:1233"), new HighWatermark(50000) });
new SocketOption[] { new Listener(listener),
new Bind("tcp://127.0.0.1:1233"), new HighWatermark(50000) });
//#high-watermark
}
@ -139,20 +139,23 @@ public class ZeromqDocTestBase {
}
}
static
//#listener-actor
public static class ListenerActor extends UntypedActor {
public class ListenerActor extends UntypedActor {
public void onReceive(Object message) throws Exception {
//...
}
}
//#listener-actor
static
//#health
public final Object TICK = "TICK";
public static final Object TICK = "TICK";
public static class Heap implements Serializable {
//#health
static
//#health
public class Heap implements Serializable {
public final long timestamp;
public final long used;
public final long max;
@ -164,7 +167,10 @@ public class ZeromqDocTestBase {
}
}
public static class Load implements Serializable {
//#health
static
//#health
public class Load implements Serializable {
public final long timestamp;
public final double loadAverage;
@ -174,9 +180,13 @@ public class ZeromqDocTestBase {
}
}
public static class HealthProbe extends UntypedActor {
//#health
static
//#health
public class HealthProbe extends UntypedActor {
ActorRef pubSocket = ZeroMQExtension.get(getContext().system()).newPubSocket(new Bind("tcp://127.0.0.1:1237"));
ActorRef pubSocket = ZeroMQExtension.get(getContext().system()).newPubSocket(
new Bind("tcp://127.0.0.1:1237"));
MemoryMXBean memory = ManagementFactory.getMemoryMXBean();
OperatingSystemMXBean os = ManagementFactory.getOperatingSystemMXBean();
Serialization ser = SerializationExtension.get(getContext().system());
@ -184,7 +194,8 @@ public class ZeromqDocTestBase {
@Override
public void preStart() {
getContext().system().scheduler()
.schedule(Duration.create(1, "second"), Duration.create(1, "second"), getSelf(), TICK, getContext().dispatcher());
.schedule(Duration.create(1, "second"), Duration.create(1, "second"),
getSelf(), TICK, getContext().dispatcher());
}
@Override
@ -202,25 +213,29 @@ public class ZeromqDocTestBase {
byte[] heapPayload = ser.serializerFor(Heap.class).toBinary(
new Heap(timestamp, currentHeap.getUsed(), currentHeap.getMax()));
// the first frame is the topic, second is the message
pubSocket.tell(new ZMQMessage(new Frame("health.heap"), new Frame(heapPayload)), getSelf());
pubSocket.tell(new ZMQMessage(new Frame("health.heap"),
new Frame(heapPayload)), getSelf());
// use akka SerializationExtension to convert to bytes
byte[] loadPayload = ser.serializerFor(Load.class).toBinary(new Load(timestamp, os.getSystemLoadAverage()));
byte[] loadPayload = ser.serializerFor(Load.class).toBinary(
new Load(timestamp, os.getSystemLoadAverage()));
// the first frame is the topic, second is the message
pubSocket.tell(new ZMQMessage(new Frame("health.load"), new Frame(loadPayload)), getSelf());
pubSocket.tell(new ZMQMessage(new Frame("health.load"),
new Frame(loadPayload)), getSelf());
} else {
unhandled(message);
}
}
}
//#health
static
//#logger
public static class Logger extends UntypedActor {
public class Logger extends UntypedActor {
ActorRef subSocket = ZeroMQExtension.get(getContext().system()).newSubSocket(new Connect("tcp://127.0.0.1:1237"),
ActorRef subSocket = ZeroMQExtension.get(getContext().system()).newSubSocket(
new Connect("tcp://127.0.0.1:1237"),
new Listener(getSelf()), new Subscribe("health"));
Serialization ser = SerializationExtension.get(getContext().system());
SimpleDateFormat timestampFormat = new SimpleDateFormat("HH:mm:ss.SSS");
@ -233,10 +248,12 @@ public class ZeromqDocTestBase {
// the first frame is the topic, second is the message
if (m.firstFrameAsString().equals("health.heap")) {
Heap heap = (Heap) ser.serializerFor(Heap.class).fromBinary(m.payload(1));
log.info("Used heap {} bytes, at {}", heap.used, timestampFormat.format(new Date(heap.timestamp)));
log.info("Used heap {} bytes, at {}", heap.used,
timestampFormat.format(new Date(heap.timestamp)));
} else if (m.firstFrameAsString().equals("health.load")) {
Load load = (Load) ser.serializerFor(Load.class).fromBinary(m.payload(1));
log.info("Load average {}, at {}", load.loadAverage, timestampFormat.format(new Date(load.timestamp)));
log.info("Load average {}, at {}", load.loadAverage,
timestampFormat.format(new Date(load.timestamp)));
}
} else {
unhandled(message);
@ -247,11 +264,13 @@ public class ZeromqDocTestBase {
//#logger
static
//#alerter
public static class HeapAlerter extends UntypedActor {
public class HeapAlerter extends UntypedActor {
ActorRef subSocket = ZeroMQExtension.get(getContext().system()).newSubSocket(new Connect("tcp://127.0.0.1:1237"),
new Listener(getSelf()), new Subscribe("health.heap"));
ActorRef subSocket = ZeroMQExtension.get(getContext().system()).newSubSocket(
new Connect("tcp://127.0.0.1:1237"),
new Listener(getSelf()), new Subscribe("health.heap"));
Serialization ser = SerializationExtension.get(getContext().system());
LoggingAdapter log = Logging.getLogger(getContext().system(), this);
int count = 0;
@ -269,7 +288,8 @@ public class ZeromqDocTestBase {
count = 0;
}
if (count > 10) {
log.warning("Need more memory, using {} %", (100.0 * heap.used / heap.max));
log.warning("Need more memory, using {} %",
(100.0 * heap.used / heap.max));
}
}
} else {

View file

@ -26,12 +26,18 @@ So let's create a sample extension that just lets us count the number of times s
First, we define what our ``Extension`` should do:
.. includecode:: code/docs/extension/ExtensionDocTestBase.java
:include: imports,extension
:include: imports
.. includecode:: code/docs/extension/ExtensionDocTestBase.java
:include: extension
Then we need to create an ``ExtensionId`` for our extension so we can grab ahold of it.
.. includecode:: code/docs/extension/ExtensionDocTestBase.java
:include: imports,extensionid
:include: imports
.. includecode:: code/docs/extension/ExtensionDocTestBase.java
:include: extensionid
Wicked! Now all we need to do is to actually use it:
@ -78,8 +84,10 @@ Sample configuration:
The ``Extension``:
.. includecode:: code/docs/extension/SettingsExtensionDocTestBase.java
:include: imports,extension,extensionid
:include: imports
.. includecode:: code/docs/extension/SettingsExtensionDocTestBase.java
:include: extension,extensionid
Use it:

View file

@ -20,7 +20,10 @@ it will use its default dispatcher as the ``ExecutionContext``, or you can use t
by the ``ExecutionContexts`` class to wrap ``Executors`` and ``ExecutorServices``, or even create your own.
.. includecode:: code/docs/future/FutureDocTestBase.java
:include: imports1,imports7,diy-execution-context
:include: imports1,imports7
.. includecode:: code/docs/future/FutureDocTestBase.java
:include: diy-execution-context
Use with Actors
---------------
@ -32,7 +35,10 @@ Using the ``ActorRef``\'s ``ask`` method to send a message will return a ``Futur
To wait for and retrieve the actual result the simplest method is:
.. includecode:: code/docs/future/FutureDocTestBase.java
:include: imports1,ask-blocking
:include: imports1
.. includecode:: code/docs/future/FutureDocTestBase.java
:include: ask-blocking
This will cause the current thread to block and wait for the ``UntypedActor`` to 'complete' the ``Future`` with it's reply.
Blocking is discouraged though as it can cause performance problem.
@ -49,7 +55,10 @@ the extra utility of an ``UntypedActor``. If you find yourself creating a pool o
of performing a calculation in parallel, there is an easier (and faster) way:
.. includecode:: code/docs/future/FutureDocTestBase.java
:include: imports2,future-eval
:include: imports2
.. includecode:: code/docs/future/FutureDocTestBase.java
:include: future-eval
In the above code the block passed to ``future`` will be executed by the default ``Dispatcher``,
with the return value of the block used to complete the ``Future`` (in this case, the result would be the string: "HelloWorld").
@ -80,7 +89,10 @@ some operation on the result of the ``Future``, and returning a new result.
The return value of the ``map`` method is another ``Future`` that will contain the new result:
.. includecode:: code/docs/future/FutureDocTestBase.java
:include: imports2,map
:include: imports2
.. includecode:: code/docs/future/FutureDocTestBase.java
:include: map
In this example we are joining two strings together within a ``Future``. Instead of waiting for f1 to complete,
we apply our function that calculates the length of the string using the ``map`` method.
@ -131,7 +143,10 @@ It is very often desirable to be able to combine different Futures with each oth
below are some examples on how that can be done in a non-blocking fashion.
.. includecode:: code/docs/future/FutureDocTestBase.java
:include: imports3,sequence
:include: imports3
.. includecode:: code/docs/future/FutureDocTestBase.java
:include: sequence
To better explain what happened in the example, ``Future.sequence`` is taking the ``Iterable<Future<Integer>>``
and turning it into a ``Future<Iterable<Integer>>``. We can then use ``map`` to work with the ``Iterable<Integer>`` directly,
@ -141,7 +156,10 @@ The ``traverse`` method is similar to ``sequence``, but it takes a sequence of `
and returns a ``Future<Iterable<B>>``, enabling parallel ``map`` over the sequence, if you use ``Futures.future`` to create the ``Future``.
.. includecode:: code/docs/future/FutureDocTestBase.java
:include: imports4,traverse
:include: imports4
.. includecode:: code/docs/future/FutureDocTestBase.java
:include: traverse
It's as simple as that!
@ -152,7 +170,10 @@ and then applies the function to all elements in the sequence of futures, non-bl
the execution will be started when the last of the Futures is completed.
.. includecode:: code/docs/future/FutureDocTestBase.java
:include: imports5,fold
:include: imports5
.. includecode:: code/docs/future/FutureDocTestBase.java
:include: fold
That's all it takes!
@ -162,7 +183,10 @@ In some cases you don't have a start-value and you're able to use the value of t
in the sequence as the start-value, you can use ``reduce``, it works like this:
.. includecode:: code/docs/future/FutureDocTestBase.java
:include: imports6,reduce
:include: imports6
.. includecode:: code/docs/future/FutureDocTestBase.java
:include: reduce
Same as with ``fold``, the execution will be started when the last of the Futures is completed, you can also parallelize
it by chunking your futures into sub-sequences and reduce them, and then reduce the reduced results again.
@ -242,4 +266,7 @@ After
``akka.pattern.Patterns.after`` makes it easy to complete a ``Future`` with a value or exception after a timeout.
.. includecode:: code/docs/future/FutureDocTestBase.java
:include: imports8,after
:include: imports8
.. includecode:: code/docs/future/FutureDocTestBase.java
:include: after

View file

@ -12,7 +12,10 @@ Create a ``LoggingAdapter`` and use the ``error``, ``warning``, ``info``, or ``d
as illustrated in this example:
.. includecode:: code/docs/event/LoggingDocTestBase.java
:include: imports,my-actor
:include: imports
.. includecode:: code/docs/event/LoggingDocTestBase.java
:include: my-actor
The first parameter to ``Logging.getLogger`` could also be any
:class:`LoggingBus`, specifically ``system.eventStream()``; in the demonstrated
@ -74,7 +77,7 @@ by Actors:
akka {
actor {
debug {
# enable DEBUG logging of all AutoReceiveMessages (Kill, PoisonPill and the like)
# enable DEBUG logging of all AutoReceiveMessages (Kill, PoisonPill et.c.)
autoreceive = on
}
}
@ -129,7 +132,8 @@ If you want to see all messages that are sent through remoting at DEBUG log leve
akka {
remote {
# If this is "on", Akka will log all outbound messages at DEBUG level, if off then they are not logged
# If this is "on", Akka will log all outbound messages at DEBUG level,
# if off then they are not logged
log-sent-messages = on
}
}
@ -141,7 +145,8 @@ If you want to see all messages that are received through remoting at DEBUG log
akka {
remote {
# If this is "on", Akka will log all inbound messages at DEBUG level, if off then they are not logged
# If this is "on", Akka will log all inbound messages at DEBUG level,
# if off then they are not logged
log-received-messages = on
}
}
@ -171,8 +176,10 @@ event handler available in the 'akka-slf4j' module.
Example of creating a listener:
.. includecode:: code/docs/event/LoggingDocTestBase.java
:include: imports,imports-listener,my-event-listener
:include: imports,imports-listener
.. includecode:: code/docs/event/LoggingDocTestBase.java
:include: my-event-listener
.. _slf4j-java:
@ -218,7 +225,7 @@ the first case and ``LoggerFactory.getLogger(String s)`` in the second).
.. code-block:: scala
final LoggingAdapter log = Logging.getLogger(system.eventStream(), "my.nice.string");
final LoggingAdapter log = Logging.getLogger(system.eventStream(), "my.string");
Logging Thread and Akka Source in MDC
-------------------------------------

View file

@ -65,11 +65,11 @@ Looking up Remote Actors
``actorFor(path)`` will obtain an ``ActorRef`` to an Actor on a remote node::
ActorRef actor = context.actorFor("akka://app@10.0.0.1:2552/user/serviceA/retrieval");
ActorRef actor = context.actorFor("akka://app@10.0.0.1:2552/user/serviceA/worker");
As you can see from the example above the following pattern is used to find an ``ActorRef`` on a remote node::
akka://<actorsystemname>@<hostname>:<port>/<actor path>
akka://<actorsystemname>@<hostname>:<port>/<actor path>
Once you obtained a reference to the actor you can interact with it they same way you would with a local actor, e.g.::

View file

@ -304,10 +304,16 @@ the same time for one router. The ``withHashMapper`` is tried first.
Code example:
.. includecode:: code/docs/jrouting/ConsistentHashingRouterDocTestBase.java
:include: imports1,cache-actor
:include: imports1
.. includecode:: code/docs/jrouting/ConsistentHashingRouterDocTestBase.java
:include: imports2,consistent-hashing-router
:include: cache-actor
.. includecode:: code/docs/jrouting/ConsistentHashingRouterDocTestBase.java
:include: imports2
.. includecode:: code/docs/jrouting/ConsistentHashingRouterDocTestBase.java
:include: consistent-hashing-router
In the above example you see that the ``Get`` message implements ``ConsistentHashable`` itself,
while the ``Entry`` message is wrapped in a ``ConsistentHashableEnvelope``. The ``Evict``

View file

@ -25,14 +25,26 @@ scheduled operation.
Some examples
-------------
Schedule to send the "foo"-message to the testActor after 50ms:
.. includecode:: code/docs/actor/SchedulerDocTestBase.java
:include: imports1,schedule-one-off-message
:include: imports1
.. includecode:: code/docs/actor/SchedulerDocTestBase.java
:include: schedule-one-off-message
Schedule a Runnable, that sends the current time to the testActor, to be executed after 50ms:
.. includecode:: code/docs/actor/SchedulerDocTestBase.java
:include: schedule-one-off-thunk
Schedule to send the "Tick"-message to the ``tickActor`` after 0ms repeating every 50ms:
.. includecode:: code/docs/actor/SchedulerDocTestBase.java
:include: imports1,imports2,schedule-recurring
:include: imports1,imports2
.. includecode:: code/docs/actor/SchedulerDocTestBase.java
:include: schedule-recurring
From ``akka.actor.ActorSystem``
-------------------------------

View file

@ -76,7 +76,10 @@ If you want to programmatically serialize/deserialize using Akka Serialization,
here's some examples:
.. includecode:: code/docs/serialization/SerializationDocTestBase.java
:include: imports,programmatic
:include: imports
.. includecode:: code/docs/serialization/SerializationDocTestBase.java
:include: programmatic
For more information, have a look at the ``ScalaDoc`` for ``akka.serialization._``
@ -94,7 +97,10 @@ First you need to create a class definition of your ``Serializer``,
which is done by extending ``akka.serialization.JSerializer``, like this:
.. includecode:: code/docs/serialization/SerializationDocTestBase.java
:include: imports,my-own-serializer
:include: imports
.. includecode:: code/docs/serialization/SerializationDocTestBase.java
:include: my-own-serializer
:exclude: ...
Then you only need to fill in the blanks, bind it to a name in your :ref:`configuration` and then
@ -107,7 +113,10 @@ All ActorRefs are serializable using JavaSerializer, but in case you are writing
you might want to know how to serialize and deserialize them properly, here's the magic incantation:
.. includecode:: code/docs/serialization/SerializationDocTestBase.java
:include: imports,actorref-serializer
:include: imports
.. includecode:: code/docs/serialization/SerializationDocTestBase.java
:include: actorref-serializer
.. note::

View file

@ -53,16 +53,21 @@ Creating Typed Actors
To create a Typed Actor you need to have one or more interfaces, and one implementation.
The following imports are assumed:
.. includecode:: code/docs/actor/TypedActorDocTestBase.java
:include: imports
Our example interface:
.. includecode:: code/docs/actor/TypedActorDocTestBase.java
:include: imports,typed-actor-iface
:include: typed-actor-iface
:exclude: typed-actor-iface-methods
Our example implementation of that interface:
.. includecode:: code/docs/actor/TypedActorDocTestBase.java
:include: imports,typed-actor-impl
:include: typed-actor-impl
:exclude: typed-actor-impl-methods
The most trivial way of creating a Typed Actor instance
@ -81,12 +86,12 @@ Since you supply a ``Props``, you can specify which dispatcher to use, what the
Now, our ``Squarer`` doesn't have any methods, so we'd better add those.
.. includecode:: code/docs/actor/TypedActorDocTestBase.java
:include: imports,typed-actor-iface
:include: typed-actor-iface
Alright, now we've got some methods we can call, but we need to implement those in ``SquarerImpl``.
.. includecode:: code/docs/actor/TypedActorDocTestBase.java
:include: imports,typed-actor-impl
:include: typed-actor-impl
Excellent, now we have an interface and an implementation of that interface,
and we know how to create a Typed Actor from that, so let's look at calling these methods.

View file

@ -61,7 +61,10 @@ Creating Actors with default constructor
----------------------------------------
.. includecode:: code/docs/actor/UntypedActorDocTestBase.java
:include: imports,system-actorOf
:include: imports
.. includecode:: code/docs/actor/UntypedActorDocTestBase.java
:include: system-actorOf
The call to :meth:`actorOf` returns an instance of ``ActorRef``. This is a handle to
the ``UntypedActor`` instance which you can use to interact with the ``UntypedActor``. The
@ -248,8 +251,8 @@ actors may look up other actors by specifying absolute or relative
paths—logical or physical—and receive back an :class:`ActorRef` with the
result::
getContext().actorFor("/user/serviceA/aggregator") // will look up this absolute path
getContext().actorFor("../joe") // will look up sibling beneath same supervisor
getContext().actorFor("/user/serviceA/actor") // will look up this absolute path
getContext().actorFor("../joe") // will look up sibling beneath same supervisor
The supplied path is parsed as a :class:`java.net.URI`, which basically means
that it is split on ``/`` into path elements. If the path starts with ``/``, it
@ -499,7 +502,10 @@ in the mailbox.
Use it like this:
.. includecode:: code/docs/actor/UntypedActorDocTestBase.java
:include: import-actors,poison-pill
:include: import-actors
.. includecode:: code/docs/actor/UntypedActorDocTestBase.java
:include: poison-pill
Graceful Stop
-------------
@ -508,7 +514,10 @@ Graceful Stop
termination of several actors:
.. includecode:: code/docs/actor/UntypedActorDocTestBase.java
:include: import-gracefulStop,gracefulStop
:include: import-gracefulStop
.. includecode:: code/docs/actor/UntypedActorDocTestBase.java
:include: gracefulStop
When ``gracefulStop()`` returns successfully, the actors ``postStop()`` hook
will have been executed: there exists a happens-before edge between the end of
@ -542,7 +551,10 @@ The hotswapped code is kept in a Stack which can be pushed and popped.
To hotswap the Actor using ``getContext().become``:
.. includecode:: code/docs/actor/UntypedActorDocTestBase.java
:include: import-procedure,hot-swap-actor
:include: import-procedure
.. includecode:: code/docs/actor/UntypedActorDocTestBase.java
:include: hot-swap-actor
The ``become`` method is useful for many different things, such as to implement
a Finite State Machine (FSM).
@ -622,7 +634,10 @@ through regular supervisor semantics.
Use it like this:
.. includecode:: code/docs/actor/UntypedActorDocTestBase.java
:include: import-actors,kill
:include: import-actors
.. includecode:: code/docs/actor/UntypedActorDocTestBase.java
:include: kill
Actors and exceptions
=====================

View file

@ -19,12 +19,16 @@ Connection
ZeroMQ supports multiple connectivity patterns, each aimed to meet a different set of requirements. Currently, this module supports publisher-subscriber connections and connections based on dealers and routers. For connecting or accepting connections, a socket must be created.
Sockets are always created using the ``akka.zeromq.ZeroMQExtension``, for example:
.. includecode:: code/docs/zeromq/ZeromqDocTestBase.java#import-pub-socket
.. includecode:: code/docs/zeromq/ZeromqDocTestBase.java#pub-socket
Above examples will create a ZeroMQ Publisher socket that is Bound to the port 21231 on localhost.
Similarly you can create a subscription socket, with a listener, that subscribes to all messages from the publisher using:
.. includecode:: code/docs/zeromq/ZeromqDocTestBase.java#import-sub-socket
.. includecode:: code/docs/zeromq/ZeromqDocTestBase.java#sub-socket
.. includecode:: code/docs/zeromq/ZeromqDocTestBase.java#listener-actor
@ -50,10 +54,14 @@ It is a prefix match so it is subscribed to all topics starting with ``foo.bar``
To unsubscribe from a topic you do the following:
.. includecode:: code/docs/zeromq/ZeromqDocTestBase.java#import-unsub-topic-socket
.. includecode:: code/docs/zeromq/ZeromqDocTestBase.java#unsub-topic-socket
To publish messages to a topic you must use two Frames with the topic in the first frame.
.. includecode:: code/docs/zeromq/ZeromqDocTestBase.java#import-pub-topic
.. includecode:: code/docs/zeromq/ZeromqDocTestBase.java#pub-topic
Pub-Sub in Action
@ -64,6 +72,8 @@ The following example illustrates one publisher with two subscribers.
The publisher monitors current heap usage and system load and periodically publishes ``Heap`` events on the ``"health.heap"`` topic
and ``Load`` events on the ``"health.load"`` topic.
.. includecode:: code/docs/zeromq/ZeromqDocTestBase.java#import-health
.. includecode:: code/docs/zeromq/ZeromqDocTestBase.java#health
.. includecode:: code/docs/zeromq/ZeromqDocTestBase.java#health2

View file

@ -58,10 +58,14 @@ import scala.concurrent.util.duration._
class MyMailboxType(systemSettings: ActorSystem.Settings, config: Config)
extends MailboxType {
override def create(owner: Option[ActorRef], system: Option[ActorSystem]): MessageQueue = (owner zip system) headOption match {
case Some((o, s: ExtendedActorSystem)) new MyMessageQueue(o, s)
case _ throw new IllegalArgumentException("requires an owner (i.e. does not work with BalancingDispatcher)")
}
override def create(owner: Option[ActorRef],
system: Option[ActorSystem]): MessageQueue =
(owner zip system) headOption match {
case Some((o, s: ExtendedActorSystem)) new MyMessageQueue(o, s)
case _
throw new IllegalArgumentException("requires an owner " +
"(i.e. does not work with BalancingDispatcher)")
}
}
class MyMessageQueue(_owner: ActorRef, _system: ExtendedActorSystem)
@ -72,10 +76,11 @@ class MyMessageQueue(_owner: ActorRef, _system: ExtendedActorSystem)
// three parameters below
val breaker = CircuitBreaker(system.scheduler, 5, 30.seconds, 1.minute)
def enqueue(receiver: ActorRef, envelope: Envelope): Unit = breaker.withSyncCircuitBreaker {
val data: Array[Byte] = serialize(envelope)
storage.push(data)
}
def enqueue(receiver: ActorRef, envelope: Envelope): Unit =
breaker.withSyncCircuitBreaker {
val data: Array[Byte] = serialize(envelope)
storage.push(data)
}
def dequeue(): Envelope = breaker.withSyncCircuitBreaker {
val data: Option[Array[Byte]] = storage.pull()

View file

@ -66,11 +66,12 @@ Java:
::
// Use this Actors' Dispatcher as ExecutionContext
getContext().system().scheduler().scheduleOnce(Duration.parse("10 seconds", getSelf(),
new Reconnect(), getContext().getDispatcher());
getContext().system().scheduler().scheduleOnce(Duration.parse("10 seconds",
getSelf(), new Reconnect(), getContext().getDispatcher());
// Use ActorSystem's default Dispatcher as ExecutionContext
system.scheduler().scheduleOnce(Duration.create(50, TimeUnit.MILLISECONDS), new Runnable() {
system.scheduler().scheduleOnce(Duration.create(50, TimeUnit.MILLISECONDS),
new Runnable() {
@Override
public void run() {
testActor.tell(System.currentTimeMillis());
@ -98,7 +99,8 @@ v2.0::
v2.1::
val failedFilter = future1.filter(_ % 2 == 1).recover {
case m: NoSuchElementException => //When filter fails, it will have a java.util.NoSuchElementException
// When filter fails, it will have a java.util.NoSuchElementException
case m: NoSuchElementException =>
}
@ -112,10 +114,10 @@ v2.0::
ExecutionContextExecutorService ec =
ExecutionContexts.fromExecutorService(yourExecutorServiceGoesHere);
//Use ec with your Futures
// Use ec with your Futures
Future<String> f1 = Futures.successful("foo", ec);
// Then you shut the ec down somewhere at the end of your program/application.
// Then you shut the ec down somewhere at the end of your application.
ec.shutdown();
v2.1::
@ -127,7 +129,7 @@ v2.1::
//No need to pass the ExecutionContext here
Future<String> f1 = Futures.successful("foo");
// Then you shut the ExecutorService down somewhere at the end of your program/application.
// Then you shut the ExecutorService down somewhere at the end of your application.
yourExecutorServiceGoesHere.shutdown();
v2.0::
@ -166,7 +168,8 @@ v2.0::
v2.1::
final ExecutionContext ec = system.dispatcher();
Future<String> future1 = Futures.successful("value").andThen(new OnComplete<String>() {
Future<String> future1 = Futures.successful("value").andThen(
new OnComplete<String>() {
public void onComplete(Throwable failure, String result) {
if (failure != null)
sendToIssueTracker(failure);
@ -210,7 +213,8 @@ v2.0 Java::
v2.1 Java::
ActorRef router2 = system.actorOf(new Props().withRouter(RoundRobinRouter.create(routees)));
ActorRef router2 = system.actorOf(new Props().withRouter(
RoundRobinRouter.create(routees)));
Props: Function-based creation
==============================
@ -337,7 +341,8 @@ v2.0::
val newRoutees = routeeProvider.createRoutees(props, requestedCapacity, Nil)
routeeProvider.registerRoutees(newRoutees)
} else if (requestedCapacity < 0) {
val (keep, abandon) = currentRoutees.splitAt(currentRoutees.length + requestedCapacity)
val (keep, abandon) = currentRoutees.splitAt(currentRoutees.length +
requestedCapacity)
routeeProvider.unregisterRoutees(abandon)
delayedStop(routeeProvider.context.system.scheduler, abandon)(
routeeProvider.context.dispatcher)
@ -379,7 +384,7 @@ v2.0::
v2.1::
final FiniteDuration d = Duration.create("1 second");
final Timeout t = new Timeout(d); // always required finite duration, now also in type
final Timeout t = new Timeout(d); // always required finite duration, now enforced
Package Name Changes in Remoting
================================

View file

@ -353,7 +353,7 @@ paths—logical or physical—and receive back an :class:`ActorRef` with the
result::
context.actorFor("/user/serviceA/aggregator") // will look up this absolute path
context.actorFor("../joe") // will look up sibling beneath same supervisor
context.actorFor("../joe") // will look up sibling beneath same supervisor
The supplied path is parsed as a :class:`java.net.URI`, which basically means
that it is split on ``/`` into path elements. If the path starts with ``/``, it

View file

@ -235,7 +235,8 @@ class ActorDocSpec extends AkkaSpec(Map("akka.loglevel" -> "INFO")) {
"creating actor with Props" in {
//#creating-props
import akka.actor.Props
val myActor = system.actorOf(Props[MyActor].withDispatcher("my-dispatcher"), name = "myactor2")
val myActor = system.actorOf(Props[MyActor].withDispatcher("my-dispatcher"),
name = "myactor2")
//#creating-props
system.stop(myActor)
@ -354,7 +355,8 @@ class ActorDocSpec extends AkkaSpec(Map("akka.loglevel" -> "INFO")) {
Await.result(stopped, 6 seconds)
// the actor has been stopped
} catch {
case e: akka.pattern.AskTimeoutException // the actor wasn't stopped within 5 seconds
// the actor wasn't stopped within 5 seconds
case e: akka.pattern.AskTimeoutException
}
//#gracefulStop
}

View file

@ -87,7 +87,8 @@ class Worker extends Actor with ActorLogging {
case _: CounterService.ServiceUnavailable Stop
}
// The sender of the initial Start message will continuously be notified about progress
// The sender of the initial Start message will continuously be notified
// about progress
var progressListener: Option[ActorRef] = None
val counterService = context.actorOf(Props[CounterService], name = "counter")
val totalCount = 51
@ -133,9 +134,10 @@ class CounterService extends Actor {
// Restart the storage child when StorageException is thrown.
// After 3 restarts within 5 seconds it will be stopped.
override val supervisorStrategy = OneForOneStrategy(maxNrOfRetries = 3, withinTimeRange = 5 seconds) {
case _: Storage.StorageException Restart
}
override val supervisorStrategy = OneForOneStrategy(maxNrOfRetries = 3,
withinTimeRange = 5 seconds) {
case _: Storage.StorageException Restart
}
val key = self.path.name
var storage: Option[ActorRef] = None
@ -194,14 +196,15 @@ class CounterService extends Actor {
}
def forwardOrPlaceInBacklog(msg: Any) {
// We need the initial value from storage before we can start delegate to the counter.
// Before that we place the messages in a backlog, to be sent to the counter when
// it is initialized.
// We need the initial value from storage before we can start delegate to
// the counter. Before that we place the messages in a backlog, to be sent
// to the counter when it is initialized.
counter match {
case Some(c) c forward msg
case None
if (backlog.size >= MaxBacklog)
throw new ServiceUnavailable("CounterService not available, lack of initial value")
throw new ServiceUnavailable(
"CounterService not available, lack of initial value")
backlog = backlog :+ (sender, msg)
}
}
@ -281,7 +284,8 @@ object DummyDB {
@throws(classOf[StorageException])
def save(key: String, value: Long): Unit = synchronized {
if (11 <= value && value <= 14) throw new StorageException("Simulated store failure " + value)
if (11 <= value && value <= 14)
throw new StorageException("Simulated store failure " + value)
db += (key -> value)
}

View file

@ -24,12 +24,13 @@ object FaultHandlingDocSpec {
import akka.actor.SupervisorStrategy._
import scala.concurrent.util.duration._
override val supervisorStrategy = OneForOneStrategy(maxNrOfRetries = 10, withinTimeRange = 1 minute) {
case _: ArithmeticException Resume
case _: NullPointerException Restart
case _: IllegalArgumentException Stop
case _: Exception Escalate
}
override val supervisorStrategy =
OneForOneStrategy(maxNrOfRetries = 10, withinTimeRange = 1 minute) {
case _: ArithmeticException Resume
case _: NullPointerException Restart
case _: IllegalArgumentException Stop
case _: Exception Escalate
}
//#strategy
def receive = {
@ -45,12 +46,13 @@ object FaultHandlingDocSpec {
import akka.actor.SupervisorStrategy._
import scala.concurrent.util.duration._
override val supervisorStrategy = OneForOneStrategy(maxNrOfRetries = 10, withinTimeRange = 1 minute) {
case _: ArithmeticException Resume
case _: NullPointerException Restart
case _: IllegalArgumentException Stop
case _: Exception Escalate
}
override val supervisorStrategy =
OneForOneStrategy(maxNrOfRetries = 10, withinTimeRange = 1 minute) {
case _: ArithmeticException Resume
case _: NullPointerException Restart
case _: IllegalArgumentException Stop
case _: Exception Escalate
}
//#strategy2
def receive = {

View file

@ -55,7 +55,8 @@ trait Foo {
trait Bar {
import TypedActor.dispatcher //So we have an implicit dispatcher for our Promise
def doBar(str: String): Future[String] = Promise.successful(str.toUpperCase).future
def doBar(str: String): Future[String] =
Promise.successful(str.toUpperCase).future
}
class FooBar extends Foo with Bar
@ -106,7 +107,8 @@ class TypedActorDocSpec extends AkkaSpec(Map("akka.loglevel" -> "INFO")) {
//#typed-actor-create1
//#typed-actor-create2
val otherSquarer: Squarer =
TypedActor(system).typedActorOf(TypedProps(classOf[Squarer], new SquarerImpl("foo")), "name")
TypedActor(system).typedActorOf(TypedProps(classOf[Squarer],
new SquarerImpl("foo")), "name")
//#typed-actor-create2
//#typed-actor-calls
@ -157,7 +159,8 @@ class TypedActorDocSpec extends AkkaSpec(Map("akka.loglevel" -> "INFO")) {
try {
//#typed-actor-hierarchy
//Inside your Typed Actor
val childSquarer: Squarer = TypedActor(TypedActor.context).typedActorOf(TypedProps[SquarerImpl]())
val childSquarer: Squarer =
TypedActor(TypedActor.context).typedActorOf(TypedProps[SquarerImpl]())
//Use "childSquarer" as a Squarer
//#typed-actor-hierarchy
} catch {
@ -167,7 +170,8 @@ class TypedActorDocSpec extends AkkaSpec(Map("akka.loglevel" -> "INFO")) {
"supercharge" in {
//#typed-actor-supercharge-usage
val awesomeFooBar: Foo with Bar = TypedActor(system).typedActorOf(TypedProps[FooBar]())
val awesomeFooBar: Foo with Bar =
TypedActor(system).typedActorOf(TypedProps[FooBar]())
awesomeFooBar.doFoo(10)
val f = awesomeFooBar.doBar("yes")

View file

@ -25,7 +25,8 @@ object CustomRoute {
}
}
class CustomRouteBuilder(system: ActorSystem, responder: ActorRef) extends RouteBuilder {
class CustomRouteBuilder(system: ActorSystem, responder: ActorRef)
extends RouteBuilder {
def configure {
from("jetty:http://localhost:8877/camel/custom").to(responder)
}
@ -48,7 +49,8 @@ object CustomRoute {
def receive = {
case msg: CamelMessage throw new Exception("error: %s" format msg.body)
}
override def onRouteDefinition = (rd) rd.onException(classOf[Exception]).handled(true).transform(Builder.exceptionMessage).end
override def onRouteDefinition = (rd) rd.onException(classOf[Exception]).
handled(true).transform(Builder.exceptionMessage).end
final override def preRestart(reason: Throwable, message: Option[Any]) {
sender ! Failure(reason)

View file

@ -19,8 +19,10 @@ object CustomRouteExample {
class Transformer(producer: ActorRef) extends Actor {
def receive = {
// example: transform message body "foo" to "- foo -" and forward result to producer
case msg: CamelMessage producer.forward(msg.mapBody((body: String) "- %s -" format body))
// example: transform message body "foo" to "- foo -" and forward result
// to producer
case msg: CamelMessage
producer.forward(msg.mapBody((body: String) "- %s -" format body))
}
}
@ -38,7 +40,8 @@ object CustomRouteExample {
})
}
}
// the below lines can be added to a Boot class, so that you can run the example from a MicroKernel
// the below lines can be added to a Boot class, so that you can run the
// example from a MicroKernel
val system = ActorSystem("some-system")
val producer = system.actorOf(Props[Producer1])
val mediator = system.actorOf(Props(new Transformer(producer)))

View file

@ -21,7 +21,8 @@ object HttpExample {
def endpointUri = "jetty://http://akka.io/?bridgeEndpoint=true"
override def transformOutgoingMessage(msg: Any) = msg match {
case msg: CamelMessage msg.copy(headers = msg.headers ++ msg.headers(Set(Exchange.HTTP_PATH)))
case msg: CamelMessage msg.copy(headers = msg.headers ++
msg.headers(Set(Exchange.HTTP_PATH)))
}
override def routeResponse(msg: Any) { transformer forward msg }
@ -29,13 +30,17 @@ object HttpExample {
class HttpTransformer extends Actor {
def receive = {
case msg: CamelMessage sender ! (msg.mapBody { body: Array[Byte] new String(body).replaceAll("Akka ", "AKKA ") })
case msg: Failure sender ! msg
case msg: CamelMessage
sender ! (msg.mapBody { body: Array[Byte]
new String(body).replaceAll("Akka ", "AKKA ")
})
case msg: Failure sender ! msg
}
}
// Create the actors. this can be done in a Boot class so you can
// run the example in the MicroKernel. just add the below three lines to your boot class.
// run the example in the MicroKernel. Just add the three lines below
// to your boot class.
val system = ActorSystem("some-system")
val httpTransformer = system.actorOf(Props[HttpTransformer])
val httpProducer = system.actorOf(Props(new HttpProducer(httpTransformer)))

View file

@ -72,7 +72,8 @@ object Introduction {
val system = ActorSystem("some-system")
val camel = CamelExtension(system)
val camelContext = camel.context
// camelContext.addComponent("activemq", ActiveMQComponent.activeMQComponent("vm://localhost?broker.persistent=false"))
// camelContext.addComponent("activemq", ActiveMQComponent.activeMQComponent(
// "vm://localhost?broker.persistent=false"))
//#CamelExtensionAddComponent
}
{
@ -92,12 +93,14 @@ object Introduction {
val camel = CamelExtension(system)
val actorRef = system.actorOf(Props[MyEndpoint])
// get a future reference to the activation of the endpoint of the Consumer Actor
val activationFuture = camel.activationFutureFor(actorRef)(timeout = 10 seconds, executor = system.dispatcher)
val activationFuture = camel.activationFutureFor(actorRef)(timeout = 10 seconds,
executor = system.dispatcher)
//#CamelActivation
//#CamelDeactivation
system.stop(actorRef)
// get a future reference to the deactivation of the endpoint of the Consumer Actor
val deactivationFuture = camel.deactivationFutureFor(actorRef)(timeout = 10 seconds, executor = system.dispatcher)
val deactivationFuture = camel.deactivationFutureFor(actorRef)(timeout = 10 seconds,
executor = system.dispatcher)
//#CamelDeactivation
}

View file

@ -45,7 +45,8 @@ object Producers {
}
val system = ActorSystem("some-system")
val receiver = system.actorOf(Props[ResponseReceiver])
val forwardResponse = system.actorOf(Props(new Forwarder("http://localhost:8080/news/akka", receiver)))
val forwardResponse = system.actorOf(Props(
new Forwarder("http://localhost:8080/news/akka", receiver)))
// the Forwarder sends out a request to the web page and forwards the response to
// the ResponseReceiver
forwardResponse ! "some request"

View file

@ -112,21 +112,22 @@ object DispatcherDocSpec {
// We inherit, in this case, from UnboundedPriorityMailbox
// and seed it with the priority generator
class MyPrioMailbox(settings: ActorSystem.Settings, config: Config) extends UnboundedPriorityMailbox(
// Create a new PriorityGenerator, lower prio means more important
PriorityGenerator {
// 'highpriority messages should be treated first if possible
case 'highpriority 0
class MyPrioMailbox(settings: ActorSystem.Settings, config: Config)
extends UnboundedPriorityMailbox(
// Create a new PriorityGenerator, lower prio means more important
PriorityGenerator {
// 'highpriority messages should be treated first if possible
case 'highpriority 0
// 'lowpriority messages should be treated last if possible
case 'lowpriority 2
// 'lowpriority messages should be treated last if possible
case 'lowpriority 2
// PoisonPill when no other left
case PoisonPill 3
// PoisonPill when no other left
case PoisonPill 3
// We default to 1, which is in between high and low
case otherwise 1
})
// We default to 1, which is in between high and low
case otherwise 1
})
//#prio-mailbox
class MyActor extends Actor {
@ -151,7 +152,8 @@ object DispatcherDocSpec {
def this(settings: ActorSystem.Settings, config: Config) = this()
// The create method is called to create the MessageQueue
final override def create(owner: Option[ActorRef], system: Option[ActorSystem]): MessageQueue =
final override def create(owner: Option[ActorRef],
system: Option[ActorSystem]): MessageQueue =
new QueueBasedMessageQueue with UnboundedMessageQueueSemantics {
final val queue = new ConcurrentLinkedQueue[Envelope]()
}

View file

@ -20,7 +20,9 @@ import akka.testkit.AkkaSpec
//#extension
class SettingsImpl(config: Config) extends Extension {
val DbUri: String = config.getString("myapp.db.uri")
val CircuitBreakerTimeout: Duration = Duration(config.getMilliseconds("myapp.circuit-breaker.timeout"), TimeUnit.MILLISECONDS)
val CircuitBreakerTimeout: Duration =
Duration(config.getMilliseconds("myapp.circuit-breaker.timeout"),
TimeUnit.MILLISECONDS)
}
//#extension
@ -29,7 +31,8 @@ object Settings extends ExtensionId[SettingsImpl] with ExtensionIdProvider {
override def lookup = Settings
override def createExtension(system: ExtendedActorSystem) = new SettingsImpl(system.settings.config)
override def createExtension(system: ExtendedActorSystem) =
new SettingsImpl(system.settings.config)
}
//#extensionid

View file

@ -151,7 +151,8 @@ class FutureDocSpec extends AkkaSpec {
result must be(4)
val failedFilter = future1.filter(_ % 2 == 1).recover {
case m: NoSuchElementException 0 //When filter fails, it will have a java.util.NoSuchElementException
// When filter fails, it will have a java.util.NoSuchElementException
case m: NoSuchElementException 0
}
val result2 = Await.result(failedFilter, 1 second)
result2 must be(0) //Can only be 0 when there was a MatchError
@ -258,7 +259,8 @@ class FutureDocSpec extends AkkaSpec {
"demonstrate usage of fold" in {
//#fold
val futures = for (i 1 to 1000) yield Future(i * 2) // Create a sequence of Futures
// Create a sequence of Futures
val futures = for (i 1 to 1000) yield Future(i * 2)
val futureSum = Future.fold(futures)(0)(_ + _)
Await.result(futureSum, 1 second) must be(1001000)
//#fold
@ -266,7 +268,8 @@ class FutureDocSpec extends AkkaSpec {
"demonstrate usage of reduce" in {
//#reduce
val futures = for (i 1 to 1000) yield Future(i * 2) // Create a sequence of Futures
// Create a sequence of Futures
val futures = for (i 1 to 1000) yield Future(i * 2)
val futureSum = Future.reduce(futures)(_ + _)
Await.result(futureSum, 1 second) must be(1001000)
//#reduce
@ -290,8 +293,9 @@ class FutureDocSpec extends AkkaSpec {
val msg1 = -1
//#try-recover
val future = akka.pattern.ask(actor, msg1) recoverWith {
case e: ArithmeticException Future.successful(0)
case foo: IllegalArgumentException Future.failed[Int](new IllegalStateException("All br0ken!"))
case e: ArithmeticException Future.successful(0)
case foo: IllegalArgumentException
Future.failed[Int](new IllegalStateException("All br0ken!"))
}
//#try-recover
Await.result(future, 1 second) must be(0)

View file

@ -50,10 +50,16 @@ object HttpServer {
val rsp = request match {
case Request("GET", "ping" :: Nil, _, _, headers, _)
OKResponse(ByteString("<p>pong</p>"),
request.headers.exists { case Header(n, v) n.toLowerCase == "connection" && v.toLowerCase == "keep-alive" })
request.headers.exists {
case Header(n, v)
n.toLowerCase == "connection" && v.toLowerCase == "keep-alive"
})
case req
OKResponse(ByteString("<p>" + req.toString + "</p>"),
request.headers.exists { case Header(n, v) n.toLowerCase == "connection" && v.toLowerCase == "keep-alive" })
request.headers.exists {
case Header(n, v)
n.toLowerCase == "connection" && v.toLowerCase == "keep-alive"
})
}
socket write OKResponse.bytes(rsp).compact
if (!rsp.keepAlive) socket.close()
@ -64,7 +70,8 @@ object HttpServer {
//#actor-companion
//#request-class
case class Request(meth: String, path: List[String], query: Option[String], httpver: String, headers: List[Header], body: Option[ByteString])
case class Request(meth: String, path: List[String], query: Option[String],
httpver: String, headers: List[Header], body: Option[ByteString])
case class Header(name: String, value: String)
//#request-class
@ -118,13 +125,15 @@ object HttpIteratees {
//#read-path
def readPath = {
def step(segments: List[String]): IO.Iteratee[List[String]] = IO peek 1 flatMap {
case PATH IO drop 1 flatMap (_ readUriPart(pathchar) flatMap (segment step(segment :: segments)))
case _ segments match {
case "" :: rest IO Done rest.reverse
case _ IO Done segments.reverse
def step(segments: List[String]): IO.Iteratee[List[String]] =
IO peek 1 flatMap {
case PATH IO drop 1 flatMap (_ readUriPart(pathchar) flatMap (
segment step(segment :: segments)))
case _ segments match {
case "" :: rest IO Done rest.reverse
case _ IO Done segments.reverse
}
}
}
step(Nil)
}
//#read-path
@ -140,14 +149,17 @@ object HttpIteratees {
val alpha = Set.empty ++ ('a' to 'z') ++ ('A' to 'Z') map (_.toByte)
val digit = Set.empty ++ ('0' to '9') map (_.toByte)
val hexdigit = digit ++ (Set.empty ++ ('a' to 'f') ++ ('A' to 'F') map (_.toByte))
val subdelim = Set('!', '$', '&', '\'', '(', ')', '*', '+', ',', ';', '=') map (_.toByte)
val subdelim = Set('!', '$', '&', '\'', '(', ')', '*', '+', ',', ';', '=') map
(_.toByte)
val pathchar = alpha ++ digit ++ subdelim ++ (Set(':', '@') map (_.toByte))
val querychar = pathchar ++ (Set('/', '?') map (_.toByte))
def readUriPart(allowed: Set[Byte]): IO.Iteratee[String] = for {
str IO takeWhile allowed map ascii
pchar IO peek 1 map (_ == PERCENT)
all if (pchar) readPChar flatMap (ch readUriPart(allowed) map (str + ch + _)) else IO Done str
all if (pchar) readPChar flatMap (ch readUriPart(allowed) map
(str + ch + _))
else IO Done str
} yield all
def readPChar = IO take 3 map {
@ -173,15 +185,18 @@ object HttpIteratees {
value IO takeUntil CRLF flatMap readMultiLineValue
} yield Header(ascii(name), ascii(value))
def readMultiLineValue(initial: ByteString): IO.Iteratee[ByteString] = IO peek 1 flatMap {
case SP IO takeUntil CRLF flatMap (bytes readMultiLineValue(initial ++ bytes))
case _ IO Done initial
}
def readMultiLineValue(initial: ByteString): IO.Iteratee[ByteString] =
IO peek 1 flatMap {
case SP IO takeUntil CRLF flatMap (
bytes readMultiLineValue(initial ++ bytes))
case _ IO Done initial
}
//#read-headers
//#read-body
def readBody(headers: List[Header]) =
if (headers.exists(header header.name == "Content-Length" || header.name == "Transfer-Encoding"))
if (headers.exists(header header.name == "Content-Length" ||
header.name == "Transfer-Encoding"))
IO.takeAll map (Some(_))
else
IO Done None
@ -210,7 +225,8 @@ object OKResponse {
date ++= ByteString(new java.util.Date().toString) ++= CRLF ++=
server ++= CRLF ++=
contentLength ++= ByteString(rsp.body.length.toString) ++= CRLF ++=
connection ++= (if (rsp.keepAlive) keepAlive else close) ++= CRLF ++= CRLF ++= rsp.body result
connection ++= (if (rsp.keepAlive) keepAlive else close) ++= CRLF ++=
CRLF ++= rsp.body result
}
}

View file

@ -32,7 +32,8 @@ class RemoteDeploymentDocSpec extends AkkaSpec("""
"demonstrate programmatic deployment" in {
//#deploy
val ref = system.actorOf(Props[SampleActor].withDeploy(Deploy(scope = RemoteScope(address))))
val ref = system.actorOf(Props[SampleActor].
withDeploy(Deploy(scope = RemoteScope(address))))
//#deploy
ref.path.address must be(address)
ref ! "test"

View file

@ -22,8 +22,10 @@ class RouterDocSpec extends AkkaSpec {
//#dispatchers
val router: ActorRef = system.actorOf(Props[MyActor]
.withRouter(RoundRobinRouter(5, routerDispatcher = "router")) // head will run on "router" dispatcher
.withDispatcher("workers")) // MyActor workers will run on "workers" dispatcher
// head will run on "router" dispatcher
.withRouter(RoundRobinRouter(5, routerDispatcher = "router"))
// MyActor workers will run on "workers" dispatcher
.withDispatcher("workers"))
//#dispatchers
}
}

View file

@ -66,8 +66,8 @@ class ParentActor extends Actor {
//#randomRouter
case "smr"
//#smallestMailboxRouter
val smallestMailboxRouter =
context.actorOf(Props[PrintlnActor].withRouter(SmallestMailboxRouter(5)), "router")
val smallestMailboxRouter = context.actorOf(Props[PrintlnActor].
withRouter(SmallestMailboxRouter(5)), "router")
1 to 10 foreach {
i smallestMailboxRouter ! i
}

View file

@ -40,7 +40,8 @@ class TestKitUsageSpec
val randomTail = Random.nextInt(10)
val headList = Seq().padTo(randomHead, "0")
val tailList = Seq().padTo(randomTail, "1")
val seqRef = system.actorOf(Props(new SequencingActor(testActor, headList, tailList)))
val seqRef =
system.actorOf(Props(new SequencingActor(testActor, headList, tailList)))
override def afterAll {
system.shutdown()

View file

@ -49,7 +49,8 @@ object ZeromqDocSpec {
val timestamp = System.currentTimeMillis
// use akka SerializationExtension to convert to bytes
val heapPayload = ser.serialize(Heap(timestamp, currentHeap.getUsed, currentHeap.getMax)).get
val heapPayload = ser.serialize(Heap(timestamp, currentHeap.getUsed,
currentHeap.getMax)).get
// the first frame is the topic, second is the message
pubSocket ! ZMQMessage(Seq(Frame("health.heap"), Frame(heapPayload)))
@ -64,19 +65,24 @@ object ZeromqDocSpec {
//#logger
class Logger extends Actor with ActorLogging {
ZeroMQExtension(context.system).newSocket(SocketType.Sub, Listener(self), Connect("tcp://127.0.0.1:1235"), Subscribe("health"))
ZeroMQExtension(context.system).newSocket(SocketType.Sub, Listener(self),
Connect("tcp://127.0.0.1:1235"), Subscribe("health"))
val ser = SerializationExtension(context.system)
val timestampFormat = new SimpleDateFormat("HH:mm:ss.SSS")
def receive = {
// the first frame is the topic, second is the message
case m: ZMQMessage if m.firstFrameAsString == "health.heap"
val Heap(timestamp, used, max) = ser.deserialize(m.payload(1), classOf[Heap]).get
log.info("Used heap {} bytes, at {}", used, timestampFormat.format(new Date(timestamp)))
val Heap(timestamp, used, max) = ser.deserialize(m.payload(1),
classOf[Heap]).get
log.info("Used heap {} bytes, at {}", used,
timestampFormat.format(new Date(timestamp)))
case m: ZMQMessage if m.firstFrameAsString == "health.load"
val Load(timestamp, loadAverage) = ser.deserialize(m.payload(1), classOf[Load]).get
log.info("Load average {}, at {}", loadAverage, timestampFormat.format(new Date(timestamp)))
val Load(timestamp, loadAverage) = ser.deserialize(m.payload(1),
classOf[Load]).get
log.info("Load average {}, at {}", loadAverage,
timestampFormat.format(new Date(timestamp)))
}
}
//#logger
@ -84,17 +90,20 @@ object ZeromqDocSpec {
//#alerter
class HeapAlerter extends Actor with ActorLogging {
ZeroMQExtension(context.system).newSocket(SocketType.Sub, Listener(self), Connect("tcp://127.0.0.1:1235"), Subscribe("health.heap"))
ZeroMQExtension(context.system).newSocket(SocketType.Sub,
Listener(self), Connect("tcp://127.0.0.1:1235"), Subscribe("health.heap"))
val ser = SerializationExtension(context.system)
var count = 0
def receive = {
// the first frame is the topic, second is the message
case m: ZMQMessage if m.firstFrameAsString == "health.heap"
val Heap(timestamp, used, max) = ser.deserialize(m.payload(1), classOf[Heap]).get
val Heap(timestamp, used, max) = ser.deserialize(m.payload(1),
classOf[Heap]).get
if ((used.toDouble / max) > 0.9) count += 1
else count = 0
if (count > 10) log.warning("Need more memory, using {} %", (100.0 * used / max))
if (count > 10) log.warning("Need more memory, using {} %",
(100.0 * used / max))
}
}
//#alerter
@ -109,7 +118,8 @@ class ZeromqDocSpec extends AkkaSpec("akka.loglevel=INFO") {
//#pub-socket
import akka.zeromq.ZeroMQExtension
val pubSocket = ZeroMQExtension(system).newSocket(SocketType.Pub, Bind("tcp://127.0.0.1:21231"))
val pubSocket = ZeroMQExtension(system).newSocket(SocketType.Pub,
Bind("tcp://127.0.0.1:21231"))
//#pub-socket
//#sub-socket
@ -121,11 +131,13 @@ class ZeromqDocSpec extends AkkaSpec("akka.loglevel=INFO") {
case _ //...
}
}))
val subSocket = ZeroMQExtension(system).newSocket(SocketType.Sub, Listener(listener), Connect("tcp://127.0.0.1:21231"), SubscribeAll)
val subSocket = ZeroMQExtension(system).newSocket(SocketType.Sub,
Listener(listener), Connect("tcp://127.0.0.1:21231"), SubscribeAll)
//#sub-socket
//#sub-topic-socket
val subTopicSocket = ZeroMQExtension(system).newSocket(SocketType.Sub, Listener(listener), Connect("tcp://127.0.0.1:21231"), Subscribe("foo.bar"))
val subTopicSocket = ZeroMQExtension(system).newSocket(SocketType.Sub,
Listener(listener), Connect("tcp://127.0.0.1:21231"), Subscribe("foo.bar"))
//#sub-topic-socket
//#unsub-topic-socket

View file

@ -93,7 +93,7 @@ by Actors:
akka {
actor {
debug {
# enable DEBUG logging of all AutoReceiveMessages (Kill, PoisonPill and the like)
# enable DEBUG logging of all AutoReceiveMessages (Kill, PoisonPill et.c.)
autoreceive = on
}
}
@ -148,7 +148,8 @@ If you want to see all messages that are sent through remoting at DEBUG log leve
akka {
remote {
# If this is "on", Akka will log all outbound messages at DEBUG level, if off then they are not logged
# If this is "on", Akka will log all outbound messages at DEBUG level,
# if off then they are not logged
log-sent-messages = on
}
}
@ -160,7 +161,8 @@ If you want to see all messages that are received through remoting at DEBUG log
akka {
remote {
# If this is "on", Akka will log all inbound messages at DEBUG level, if off then they are not logged
# If this is "on", Akka will log all inbound messages at DEBUG level,
# if off then they are not logged
log-received-messages = on
}
}

View file

@ -419,7 +419,13 @@ implementation called :class:`TestProbe`. The functionality is best explained
using a small example:
.. includecode:: code/docs/testkit/TestkitDocSpec.scala
:include: imports-test-probe,my-double-echo,test-probe
:include: imports-test-probe
.. includecode:: code/docs/testkit/TestkitDocSpec.scala
:include: my-double-echo
.. includecode:: code/docs/testkit/TestkitDocSpec.scala
:include: test-probe
Here a the system under test is simulated by :class:`MyDoubleEcho`, which is
supposed to mirror its input to two outputs. Attaching two test probes enables
@ -458,7 +464,10 @@ concerning volume and timing of the message flow while still keeping the
network functioning:
.. includecode:: code/docs/testkit/TestkitDocSpec.scala
:include: test-probe-forward-actors,test-probe-forward
:include: test-probe-forward-actors
.. includecode:: code/docs/testkit/TestkitDocSpec.scala
:include: test-probe-forward
The ``dest`` actor will receive the same message invocation as if no test probe
had intervened.

View file

@ -14,10 +14,12 @@ akka {
# directory below which this queue resides
directory-path = "./_mb"
# attempting to add an item after the queue reaches this size (in items) will fail.
# attempting to add an item after the queue reaches this size (in items)
# will fail.
max-items = 2147483647
# attempting to add an item after the queue reaches this size (in bytes) will fail.
# attempting to add an item after the queue reaches this size (in bytes)
# will fail.
max-size = 2147483647 bytes
# attempting to add an item larger than this size (in bytes) will fail.
@ -35,7 +37,8 @@ akka {
# maximum overflow (multiplier) of a journal file before we re-create it.
max-journal-overflow = 10
# absolute maximum size of a journal file until we rebuild it, no matter what.
# absolute maximum size of a journal file until we rebuild it,
# no matter what.
max-journal-size-absolute = 9223372036854775807 bytes
# whether to drop older items (instead of newer) when the queue is full
@ -52,10 +55,12 @@ akka {
# maximum number of failures before opening breaker
max-failures = 3
# duration of time beyond which a call is assumed to be timed out and considered a failure
# duration of time beyond which a call is assumed to be timed out and
# considered a failure
call-timeout = 3 seconds
# duration of time to wait until attempting to reset the breaker during which all calls fail-fast
# duration of time to wait until attempting to reset the breaker during
# which all calls fail-fast
reset-timeout = 30 seconds
}
}

View file

@ -19,8 +19,9 @@ akka {
serialization-bindings {
# Since com.google.protobuf.Message does not extend Serializable but GeneratedMessage
# does, need to use the more specific one here in order to avoid ambiguity
# Since com.google.protobuf.Message does not extend Serializable but
# GeneratedMessage does, need to use the more specific one here in order
# to avoid ambiguity
"com.google.protobuf.GeneratedMessage" = proto
"akka.remote.DaemonMsgCreate" = daemon-create
}
@ -29,8 +30,8 @@ akka {
default {
# if this is set to a valid remote address, the named actor will be deployed
# at that node e.g. "akka://sys@host:port"
# if this is set to a valid remote address, the named actor will be
# deployed at that node e.g. "akka://sys@host:port"
remote = ""
target {
@ -58,48 +59,56 @@ akka {
# default is a TCP-based remote transport based on Netty
transport = "akka.remote.netty.NettyRemoteTransport"
# Enable untrusted mode for full security of server managed actors, prevents system messages to be send
# by clients, e.g. messages like 'Create', 'Suspend', 'Resume', 'Terminate', 'Supervise', 'Link' etc.
# Enable untrusted mode for full security of server managed actors, prevents
# system messages to be send by clients, e.g. messages like 'Create',
# 'Suspend', 'Resume', 'Terminate', 'Supervise', 'Link' etc.
untrusted-mode = off
# Timeout for ACK of cluster operations, like checking actor out etc.
remote-daemon-ack-timeout = 30s
# If this is "on", Akka will log all inbound messages at DEBUG level, if off then they are not logged
# If this is "on", Akka will log all inbound messages at DEBUG level,
# if off then they are not logged
log-received-messages = off
# If this is "on", Akka will log all outbound messages at DEBUG level, if off then they are not logged
# If this is "on", Akka will log all outbound messages at DEBUG level,
# if off then they are not logged
log-sent-messages = off
# If this is "on", Akka will log all RemoteLifeCycleEvents at the level defined for each, if off then they are not logged
# Failures to deserialize received messages also fall under this flag.
# If this is "on", Akka will log all RemoteLifeCycleEvents at the level
# defined for each, if off then they are not logged Failures to deserialize
# received messages also fall under this flag.
log-remote-lifecycle-events = on
# Each property is annotated with (I) or (O) or (I&O), where I stands for “inbound” and O for “outbound” connections.
# The NettyRemoteTransport always starts the server role to allow inbound connections, and it starts
# active client connections whenever sending to a destination which is not yet connected; if configured
# it reuses inbound connections for replies, which is called a passive client connection (i.e. from server
# to client).
# Each property is annotated with (I) or (O) or (I&O), where I stands for
# “inbound” and O for “outbound” connections. The NettyRemoteTransport always
# starts the server role to allow inbound connections, and it starts active
# client connections whenever sending to a destination which is not yet
# connected; if configured it reuses inbound connections for replies, which
# is called a passive client connection (i.e. from server to client).
netty {
# (O) In case of increased latency / overflow how long should we wait (blocking the sender)
# until we deem the send to be cancelled?
# 0 means "never backoff", any positive number will indicate time to block at most.
# (O) In case of increased latency / overflow how long should we wait
# (blocking the sender) until we deem the send to be cancelled?
# 0 means "never backoff", any positive number will indicate the time to
# block at most.
backoff-timeout = 0ms
# (I&O) Generate your own with '$AKKA_HOME/scripts/generate_config_with_secure_cookie.sh'
# or using 'akka.util.Crypt.generateSecureCookie'
# (I&O) Generate your own with the script availbale in
# '$AKKA_HOME/scripts/generate_config_with_secure_cookie.sh' or using
# 'akka.util.Crypt.generateSecureCookie'
secure-cookie = ""
# (I) Should the remote server require that its peers share the same secure-cookie
# (defined in the 'remote' section)?
# (I) Should the remote server require that its peers share the same
# secure-cookie (defined in the 'remote' section)?
require-cookie = off
# (I) Reuse inbound connections for outbound messages
use-passive-connections = on
# (I) EXPERIMENTAL If "<id.of.dispatcher>" then the specified dispatcher will be used to accept inbound connections,
# and perform IO. If "" then dedicated threads will be used.
# (I) EXPERIMENTAL If "<id.of.dispatcher>" then the specified dispatcher
# will be used to accept inbound connections, and perform IO. If "" then
# dedicated threads will be used.
use-dispatcher-for-io = ""
# (I) The hostname or ip to bind the remoting to,
@ -111,11 +120,13 @@ akka {
# This port needs to be unique for each actor system on the same machine.
port = 2552
# (O) The address of a local network interface (IP Address) to bind to when creating
# outbound connections. Set to "" or "auto" for automatic selection of local address.
# (O) The address of a local network interface (IP Address) to bind to when
# creating outbound connections. Set to "" or "auto" for automatic selection
# of local address.
outbound-local-address = "auto"
# (I&O) Increase this if you want to be able to send messages with large payloads
# (I&O) Increase this if you want to be able to send messages with large
# payloads
message-frame-size = 1 MiB
# (O) Sets the connectTimeoutMillis of all outbound connections,
@ -125,11 +136,14 @@ akka {
# (I) Sets the size of the connection backlog
backlog = 4096
# (I) Length in akka.time-unit how long core threads will be kept alive if idling
# (I) Length in akka.time-unit how long core threads will be kept alive if
# idling
execution-pool-keepalive = 60s
# (I) Size in number of threads of the core pool of the remote execution unit.
# A value of 0 will turn this off, which is can lead to deadlocks under some configurations!
# (I) Size in number of threads of the core pool of the remote execution
# unit.
# A value of 0 will turn this off, which is can lead to deadlocks under
# some configurations!
execution-pool-size = 4
# (I) Maximum channel size, 0 for off
@ -138,16 +152,20 @@ akka {
# (I) Maximum total size of all channels, 0 for off
max-total-memory-size = 0b
# (I&O) Sets the high water mark for the in and outbound sockets, set to 0b for platform default
# (I&O) Sets the high water mark for the in and outbound sockets,
# set to 0b for platform default
write-buffer-high-water-mark = 0b
# (I&O) Sets the low water mark for the in and outbound sockets, set to 0b for platform default
# (I&O) Sets the low water mark for the in and outbound sockets,
# set to 0b for platform default
write-buffer-low-water-mark = 0b
# (I&O) Sets the send buffer size of the Sockets, set to 0b for platform default
# (I&O) Sets the send buffer size of the Sockets,
# set to 0b for platform default
send-buffer-size = 0b
# (I&O) Sets the receive buffer size of the Sockets, set to 0b for platform default
# (I&O) Sets the receive buffer size of the Sockets,
# set to 0b for platform default
receive-buffer-size = 0b
# (O) Time between reconnect attempts for active clients
@ -164,9 +182,9 @@ akka {
# A value of 0 will turn this feature off
write-timeout = 10s
# (O) Inactivity period of both reads and writes (lowest resolution is seconds)
# after which active client connection is shutdown;
# will be re-established in case of new communication requests
# (O) Inactivity period of both reads and writes (lowest resolution is
# seconds) after which active client connection is shutdown; will be
# re-established in case of new communication requests.
# A value of 0 will turn this feature off
all-timeout = 0s
@ -197,26 +215,33 @@ akka {
# 'TLSv1.1', 'TLSv1.2'
protocol = "TLSv1"
# Examples: [ "TLS_RSA_WITH_AES_128_CBC_SHA", "TLS_RSA_WITH_AES_256_CBC_SHA" ]
# You need to install the JCE Unlimited Strength Jurisdiction Policy Files to use AES 256
# Example: ["TLS_RSA_WITH_AES_128_CBC_SHA", "TLS_RSA_WITH_AES_256_CBC_SHA"]
# You need to install the JCE Unlimited Strength Jurisdiction Policy
# Files to use AES 256.
# More info here: http://docs.oracle.com/javase/7/docs/technotes/guides/security/SunProviders.html#SunJCEProvider
enabled-algorithms = ["TLS_RSA_WITH_AES_128_CBC_SHA"]
# Using /dev/./urandom is only necessary when using SHA1PRNG on Linux to prevent blocking
# It is NOT as secure because it reuses the seed
# '' => defaults to /dev/random or whatever is set in java.security for example: securerandom.source=file:/dev/random
# '/dev/./urandom' => NOT '/dev/urandom' as that doesn't work according to: http://bugs.sun.com/view_bug.do?bug_id=6202721
# Using /dev/./urandom is only necessary when using SHA1PRNG on Linux to
# prevent blocking. It is NOT as secure because it reuses the seed.
# '' => defaults to /dev/random or whatever is set in java.security for
# example: securerandom.source=file:/dev/random
# '/dev/./urandom' => NOT '/dev/urandom' as that doesn't work according
# to: http://bugs.sun.com/view_bug.do?bug_id=6202721
sha1prng-random-source = ""
# There are three options, in increasing order of security:
# "" or SecureRandom => (default)
# "SHA1PRNG" => Can be slow because of blocking issues on Linux
# "AES128CounterSecureRNG" => fastest startup and based on AES encryption algorithm
# "AES128CounterSecureRNG" => fastest startup and based on AES encryption
# algorithm
# "AES256CounterSecureRNG"
# The following use one of 3 possible seed sources, depending on availability: /dev/random, random.org and SecureRandom (provided by Java)
# The following use one of 3 possible seed sources, depending on
# availability: /dev/random, random.org and SecureRandom (provided by Java)
# "AES128CounterInetRNG"
# "AES256CounterInetRNG" (Install JCE Unlimited Strength Jurisdiction Policy Files first)
# Setting a value here may require you to supply the appropriate cipher suite (see enabled-algorithms section above)
# "AES256CounterInetRNG" (Install JCE Unlimited Strength Jurisdiction
# Policy Files first)
# Setting a value here may require you to supply the appropriate cipher
# suite (see enabled-algorithms section above)
random-number-generator = ""
}
}

View file

@ -39,7 +39,8 @@ class StatsService extends Actor {
case StatsJob(text) if text != ""
val words = text.split(" ")
val replyTo = sender // important to not close over sender
val aggregator = context.actorOf(Props(new StatsAggregator(words.size, replyTo)))
val aggregator = context.actorOf(Props(
new StatsAggregator(words.size, replyTo)))
words foreach { word
workerRouter.tell(
ConsistentHashableEnvelope(word, word), aggregator)
@ -111,7 +112,8 @@ class StatsFacade extends Actor with ActorLogging {
if (leaderAddress == cluster.selfAddress) {
if (!currentMasterCreatedByMe) {
log.info("Creating new statsService master at [{}]", leaderAddress)
currentMaster = Some(context.actorOf(Props[StatsService], name = "statsService"))
currentMaster = Some(context.actorOf(Props[StatsService],
name = "statsService"))
currentMasterCreatedByMe = true
}
} else {

View file

@ -10,33 +10,33 @@ import java.text.NumberFormat;
//#actor
public class JCreationActor extends UntypedActor {
private static final NumberFormat formatter = new DecimalFormat("#0.00");
private static final NumberFormat formatter = new DecimalFormat("#0.00");
@Override
public void onReceive(Object message) throws Exception {
if (message instanceof InternalMsg.MathOpMsg) {
// forward math op to server actor
InternalMsg.MathOpMsg msg = (InternalMsg.MathOpMsg) message;
msg.getActor().tell(msg.getMathOp(), getSelf());
} else if (message instanceof Op.MathResult) {
// receive reply from server actor
if (message instanceof Op.MultiplicationResult) {
Op.MultiplicationResult result = (Op.MultiplicationResult) message;
System.out.println("Mul result: " + result.getN1() + " * " +
result.getN2() + " = " + result.getResult());
} else if (message instanceof Op.DivisionResult) {
Op.DivisionResult result = (Op.DivisionResult) message;
System.out.println("Div result: " + result.getN1() + " / " +
result.getN2() + " = " + formatter.format(result.getResult()));
}
} else {
unhandled(message);
}
@Override
public void onReceive(Object message) throws Exception {
if (message instanceof InternalMsg.MathOpMsg) {
// forward math op to server actor
InternalMsg.MathOpMsg msg = (InternalMsg.MathOpMsg) message;
msg.getActor().tell(msg.getMathOp(), getSelf());
} else if (message instanceof Op.MathResult) {
// receive reply from server actor
if (message instanceof Op.MultiplicationResult) {
Op.MultiplicationResult result = (Op.MultiplicationResult) message;
System.out.println("Mul result: " + result.getN1() + " * " +
result.getN2() + " = " + result.getResult());
} else if (message instanceof Op.DivisionResult) {
Op.DivisionResult result = (Op.DivisionResult) message;
System.out.println("Div result: " + result.getN1() + " / " +
result.getN2() + " = " + formatter.format(result.getResult()));
}
} else {
unhandled(message);
}
}
}
//#actor

View file

@ -36,4 +36,4 @@ public class JCreationApplication implements Bootable {
system.shutdown();
}
}
// #setup
//#setup

View file

@ -21,8 +21,8 @@ public class JLookupApplication implements Bootable {
system = ActorSystem.create("LookupApplication", ConfigFactory.load()
.getConfig("remotelookup"));
actor = system.actorOf(new Props(JLookupActor.class));
remoteActor = system
.actorFor("akka://CalculatorApplication@127.0.0.1:2552/user/simpleCalculator");
remoteActor = system.actorFor(
"akka://CalculatorApplication@127.0.0.1:2552/user/simpleCalculator");
}
public void doSomething(Op.MathOp mathOp) {

View file

@ -26,7 +26,8 @@ class SimpleCalculatorActor extends Actor {
class CalculatorApplication extends Bootable {
//#setup
val system = ActorSystem("CalculatorApplication", ConfigFactory.load.getConfig("calculator"))
val system = ActorSystem("CalculatorApplication",
ConfigFactory.load.getConfig("calculator"))
val actor = system.actorOf(Props[SimpleCalculatorActor], "simpleCalculator")
//#setup

View file

@ -14,9 +14,11 @@ import akka.actor._
class CreationApplication extends Bootable {
//#setup
val system = ActorSystem("RemoteCreation", ConfigFactory.load.getConfig("remotecreation"))
val system =
ActorSystem("RemoteCreation", ConfigFactory.load.getConfig("remotecreation"))
val localActor = system.actorOf(Props[CreationActor], "creationActor")
val remoteActor = system.actorOf(Props[AdvancedCalculatorActor], "advancedCalculator")
val remoteActor =
system.actorOf(Props[AdvancedCalculatorActor], "advancedCalculator")
def doSomething(op: MathOp) = {
localActor ! (remoteActor, op)
@ -36,8 +38,10 @@ class CreationActor extends Actor {
def receive = {
case (actor: ActorRef, op: MathOp) actor ! op
case result: MathResult result match {
case MultiplicationResult(n1, n2, r) println("Mul result: %d * %d = %d".format(n1, n2, r))
case DivisionResult(n1, n2, r) println("Div result: %.0f / %d = %.2f".format(n1, n2, r))
case MultiplicationResult(n1, n2, r)
println("Mul result: %d * %d = %d".format(n1, n2, r))
case DivisionResult(n1, n2, r)
println("Div result: %.0f / %d = %.2f".format(n1, n2, r))
}
}
}
@ -48,8 +52,10 @@ object CreationApp {
val app = new CreationApplication
println("Started Creation Application")
while (true) {
if (Random.nextInt(100) % 2 == 0) app.doSomething(Multiply(Random.nextInt(20), Random.nextInt(20)))
else app.doSomething(Divide(Random.nextInt(10000), (Random.nextInt(99) + 1)))
if (Random.nextInt(100) % 2 == 0)
app.doSomething(Multiply(Random.nextInt(20), Random.nextInt(20)))
else
app.doSomething(Divide(Random.nextInt(10000), (Random.nextInt(99) + 1)))
Thread.sleep(200)
}

View file

@ -16,9 +16,11 @@ import akka.actor.{ ActorRef, Props, Actor, ActorSystem }
class LookupApplication extends Bootable {
//#setup
val system = ActorSystem("LookupApplication", ConfigFactory.load.getConfig("remotelookup"))
val system =
ActorSystem("LookupApplication", ConfigFactory.load.getConfig("remotelookup"))
val actor = system.actorOf(Props[LookupActor], "lookupActor")
val remoteActor = system.actorFor("akka://CalculatorApplication@127.0.0.1:2552/user/simpleCalculator")
val remoteActor = system.actorFor(
"akka://CalculatorApplication@127.0.0.1:2552/user/simpleCalculator")
def doSomething(op: MathOp) = {
actor ! (remoteActor, op)
@ -38,8 +40,10 @@ class LookupActor extends Actor {
def receive = {
case (actor: ActorRef, op: MathOp) actor ! op
case result: MathResult result match {
case AddResult(n1, n2, r) println("Add result: %d + %d = %d".format(n1, n2, r))
case SubtractResult(n1, n2, r) println("Sub result: %d - %d = %d".format(n1, n2, r))
case AddResult(n1, n2, r)
println("Add result: %d + %d = %d".format(n1, n2, r))
case SubtractResult(n1, n2, r)
println("Sub result: %d - %d = %d".format(n1, n2, r))
}
}
}
@ -50,8 +54,10 @@ object LookupApp {
val app = new LookupApplication
println("Started Lookup Application")
while (true) {
if (Random.nextInt(100) % 2 == 0) app.doSomething(Add(Random.nextInt(100), Random.nextInt(100)))
else app.doSomething(Subtract(Random.nextInt(100), Random.nextInt(100)))
if (Random.nextInt(100) % 2 == 0)
app.doSomething(Add(Random.nextInt(100), Random.nextInt(100)))
else
app.doSomething(Subtract(Random.nextInt(100), Random.nextInt(100)))
Thread.sleep(200)
}

View file

@ -17,7 +17,8 @@ akka {
socket-dispatcher {
# A zeromq socket needs to be pinned to the thread that created it.
# Changing this value results in weird errors and race conditions within zeromq
# Changing this value results in weird errors and race conditions within
# zeromq
executor = thread-pool-executor
type = "PinnedDispatcher"
}