Reformating configuration and examples for PDF (Java). See #2413

This commit is contained in:
Björn Antonsson 2012-09-26 10:56:25 +02:00
parent 5490bcf66d
commit 309bb53d98
42 changed files with 902 additions and 615 deletions

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""
@ -256,12 +262,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 +287,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
@ -318,8 +324,9 @@ akka {
}
# 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.
# 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 +337,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 +347,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

@ -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

@ -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

@ -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 runs on "head" dispatcher
.withRouter(new RoundRobinRouter(5).withDispatcher("head"))
// MyActor workers 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()));
@ -99,8 +105,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 +126,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 +149,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 +166,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 +184,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 +203,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

@ -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

@ -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

@ -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

@ -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"
}