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

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