Reformating configuration and examples for PDF (Java). See #2413
This commit is contained in:
parent
5490bcf66d
commit
309bb53d98
42 changed files with 902 additions and 615 deletions
|
|
@ -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) {
|
||||
|
|
|
|||
|
|
@ -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
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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();
|
||||
|
|
|
|||
|
|
@ -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 =
|
||||
|
|
|
|||
|
|
@ -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();
|
||||
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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(); }
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
|
|
|
|||
|
|
@ -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) {
|
||||
|
|
|
|||
|
|
@ -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) {
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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()));
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
|
|
|
|||
|
|
@ -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();
|
||||
|
||||
|
|
|
|||
|
|
@ -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() {
|
||||
|
|
|
|||
|
|
@ -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));
|
||||
|
|
|
|||
|
|
@ -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 {
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue