move code to src/test
* so that it compiles and tests pass * fix some additional snip references in getting started
This commit is contained in:
parent
413df8e0f4
commit
59f53e1a22
289 changed files with 45 additions and 45 deletions
|
|
@ -0,0 +1,642 @@
|
|||
/**
|
||||
* Copyright (C) 2009-2017 Lightbend Inc. <http://www.lightbend.com>
|
||||
*/
|
||||
package jdocs.persistence;
|
||||
|
||||
import akka.actor.*;
|
||||
import akka.japi.Procedure;
|
||||
import akka.pattern.BackoffSupervisor;
|
||||
import akka.persistence.*;
|
||||
import scala.concurrent.duration.Duration;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
public class LambdaPersistenceDocTest {
|
||||
|
||||
public interface SomeOtherMessage {}
|
||||
|
||||
public interface PersistentActorMethods {
|
||||
//#persistence-id
|
||||
public String persistenceId();
|
||||
//#persistence-id
|
||||
//#recovery-status
|
||||
public boolean recoveryRunning();
|
||||
public boolean recoveryFinished();
|
||||
//#recovery-status
|
||||
}
|
||||
|
||||
static Object o2 = new Object() {
|
||||
abstract class MyPersistentActor1 extends AbstractPersistentActor {
|
||||
//#recovery-disabled
|
||||
@Override
|
||||
public Recovery recovery() {
|
||||
return Recovery.none();
|
||||
}
|
||||
//#recovery-disabled
|
||||
|
||||
//#recover-on-restart-disabled
|
||||
@Override
|
||||
public void preRestart(Throwable reason, Optional<Object> message) {}
|
||||
//#recover-on-restart-disabled
|
||||
}
|
||||
|
||||
abstract class MyPersistentActor2 extends AbstractPersistentActor {
|
||||
//#recovery-custom
|
||||
@Override
|
||||
public Recovery recovery() {
|
||||
return Recovery.create(457L);
|
||||
}
|
||||
//#recovery-custom
|
||||
}
|
||||
|
||||
class MyPersistentActor4 extends AbstractPersistentActor implements PersistentActorMethods {
|
||||
//#persistence-id-override
|
||||
@Override
|
||||
public String persistenceId() {
|
||||
return "my-stable-persistence-id";
|
||||
}
|
||||
|
||||
//#persistence-id-override
|
||||
|
||||
@Override
|
||||
public Receive createReceive() {
|
||||
return receiveBuilder().
|
||||
match(String.class, cmd -> {/* ... */}).build();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Receive createReceiveRecover() {
|
||||
return receiveBuilder().
|
||||
match(String.class, evt -> {/* ... */}).build();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
//#recovery-completed
|
||||
class MyPersistentActor5 extends AbstractPersistentActor {
|
||||
|
||||
@Override public String persistenceId() {
|
||||
return "my-stable-persistence-id";
|
||||
}
|
||||
|
||||
@Override public Receive createReceiveRecover() {
|
||||
return receiveBuilder().
|
||||
match(RecoveryCompleted.class, r -> {
|
||||
// perform init after recovery, before any other messages
|
||||
// ...
|
||||
}).
|
||||
match(String.class, this::handleEvent).build();
|
||||
}
|
||||
|
||||
@Override public Receive createReceive() {
|
||||
return receiveBuilder().
|
||||
match(String.class, s -> s.equals("cmd"),
|
||||
s -> persist("evt", this::handleEvent)).build();
|
||||
}
|
||||
|
||||
private void handleEvent(String event) {
|
||||
// update state
|
||||
// ...
|
||||
}
|
||||
|
||||
}
|
||||
//#recovery-completed
|
||||
|
||||
abstract class MyPersistentActor6 extends AbstractPersistentActor {
|
||||
//#recovery-no-snap
|
||||
@Override
|
||||
public Recovery recovery() {
|
||||
return Recovery.create(SnapshotSelectionCriteria.none());
|
||||
}
|
||||
//#recovery-no-snap
|
||||
}
|
||||
|
||||
abstract class MyActor extends AbstractPersistentActor {
|
||||
//#backoff
|
||||
@Override
|
||||
public void preStart() throws Exception {
|
||||
final Props childProps = Props.create(MyPersistentActor1.class);
|
||||
final Props props = BackoffSupervisor.props(
|
||||
childProps,
|
||||
"myActor",
|
||||
Duration.create(3, TimeUnit.SECONDS),
|
||||
Duration.create(30, TimeUnit.SECONDS),
|
||||
0.2);
|
||||
getContext().actorOf(props, "mySupervisor");
|
||||
super.preStart();
|
||||
}
|
||||
//#backoff
|
||||
}
|
||||
};
|
||||
|
||||
static Object atLeastOnceExample = new Object() {
|
||||
//#at-least-once-example
|
||||
|
||||
class Msg implements Serializable {
|
||||
private static final long serialVersionUID = 1L;
|
||||
public final long deliveryId;
|
||||
public final String s;
|
||||
|
||||
public Msg(long deliveryId, String s) {
|
||||
this.deliveryId = deliveryId;
|
||||
this.s = s;
|
||||
}
|
||||
}
|
||||
|
||||
class Confirm implements Serializable {
|
||||
private static final long serialVersionUID = 1L;
|
||||
public final long deliveryId;
|
||||
|
||||
public Confirm(long deliveryId) {
|
||||
this.deliveryId = deliveryId;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
class MsgSent implements Serializable {
|
||||
private static final long serialVersionUID = 1L;
|
||||
public final String s;
|
||||
|
||||
public MsgSent(String s) {
|
||||
this.s = s;
|
||||
}
|
||||
}
|
||||
class MsgConfirmed implements Serializable {
|
||||
private static final long serialVersionUID = 1L;
|
||||
public final long deliveryId;
|
||||
|
||||
public MsgConfirmed(long deliveryId) {
|
||||
this.deliveryId = deliveryId;
|
||||
}
|
||||
}
|
||||
|
||||
class MyPersistentActor extends AbstractPersistentActorWithAtLeastOnceDelivery {
|
||||
private final ActorSelection destination;
|
||||
|
||||
public MyPersistentActor(ActorSelection destination) {
|
||||
this.destination = destination;
|
||||
}
|
||||
|
||||
@Override public String persistenceId() {
|
||||
return "persistence-id";
|
||||
}
|
||||
|
||||
@Override
|
||||
public Receive createReceive() {
|
||||
return receiveBuilder().
|
||||
match(String.class, s -> {
|
||||
persist(new MsgSent(s), evt -> updateState(evt));
|
||||
}).
|
||||
match(Confirm.class, confirm -> {
|
||||
persist(new MsgConfirmed(confirm.deliveryId), evt -> updateState(evt));
|
||||
}).
|
||||
build();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Receive createReceiveRecover() {
|
||||
return receiveBuilder().
|
||||
match(Object.class, evt -> updateState(evt)).build();
|
||||
}
|
||||
|
||||
void updateState(Object event) {
|
||||
if (event instanceof MsgSent) {
|
||||
final MsgSent evt = (MsgSent) event;
|
||||
deliver(destination, deliveryId -> new Msg(deliveryId, evt.s));
|
||||
} else if (event instanceof MsgConfirmed) {
|
||||
final MsgConfirmed evt = (MsgConfirmed) event;
|
||||
confirmDelivery(evt.deliveryId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class MyDestination extends AbstractActor {
|
||||
@Override
|
||||
public Receive createReceive() {
|
||||
return receiveBuilder()
|
||||
.match(Msg.class, msg -> {
|
||||
// ...
|
||||
getSender().tell(new Confirm(msg.deliveryId), getSelf());
|
||||
})
|
||||
.build();
|
||||
}
|
||||
}
|
||||
//#at-least-once-example
|
||||
|
||||
};
|
||||
|
||||
static Object o4 = new Object() {
|
||||
class MyPersistentActor extends AbstractPersistentActor {
|
||||
|
||||
private void updateState(String evt){}
|
||||
|
||||
//#save-snapshot
|
||||
private Object state;
|
||||
private int snapShotInterval = 1000;
|
||||
|
||||
@Override public Receive createReceive() {
|
||||
return receiveBuilder().
|
||||
match(SaveSnapshotSuccess.class, ss -> {
|
||||
SnapshotMetadata metadata = ss.metadata();
|
||||
// ...
|
||||
}).
|
||||
match(SaveSnapshotFailure.class, sf -> {
|
||||
SnapshotMetadata metadata = sf.metadata();
|
||||
// ...
|
||||
}).
|
||||
match(String.class, cmd -> {
|
||||
persist( "evt-" + cmd, e -> {
|
||||
updateState(e);
|
||||
if (lastSequenceNr() % snapShotInterval == 0 && lastSequenceNr() != 0)
|
||||
saveSnapshot(state);
|
||||
});
|
||||
}).build();
|
||||
}
|
||||
//#save-snapshot
|
||||
|
||||
@Override public String persistenceId() {
|
||||
return "persistence-id";
|
||||
}
|
||||
|
||||
@Override public Receive createReceiveRecover() {
|
||||
return receiveBuilder().
|
||||
match(RecoveryCompleted.class, r -> {/* ...*/}).build();
|
||||
}
|
||||
|
||||
}
|
||||
};
|
||||
|
||||
static Object o5 = new Object() {
|
||||
|
||||
class MyPersistentActor extends AbstractPersistentActor {
|
||||
|
||||
//#snapshot-criteria
|
||||
@Override
|
||||
public Recovery recovery() {
|
||||
return Recovery.create(
|
||||
SnapshotSelectionCriteria
|
||||
.create(457L, System.currentTimeMillis()));
|
||||
}
|
||||
//#snapshot-criteria
|
||||
|
||||
//#snapshot-offer
|
||||
private Object state;
|
||||
|
||||
@Override public Receive createReceiveRecover() {
|
||||
return receiveBuilder().
|
||||
match(SnapshotOffer.class, s -> {
|
||||
state = s.snapshot();
|
||||
// ...
|
||||
}).
|
||||
match(String.class, s -> {/* ...*/}).build();
|
||||
}
|
||||
//#snapshot-offer
|
||||
|
||||
@Override public String persistenceId() {
|
||||
return "persistence-id";
|
||||
}
|
||||
|
||||
@Override public Receive createReceive() {
|
||||
return receiveBuilder().
|
||||
match(String.class, s -> {/* ...*/}).build();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
class MyActor extends AbstractActor {
|
||||
private final ActorRef persistentActor =
|
||||
getContext().actorOf(Props.create(MyPersistentActor.class));
|
||||
|
||||
@Override
|
||||
public Receive createReceive() {
|
||||
return receiveBuilder()
|
||||
.match(Object.class, o -> {/* ... */})
|
||||
.build();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
static Object o9 = new Object() {
|
||||
//#persist-async
|
||||
class MyPersistentActor extends AbstractPersistentActor {
|
||||
|
||||
@Override public String persistenceId() {
|
||||
return "my-stable-persistence-id";
|
||||
}
|
||||
|
||||
private void handleCommand(String c) {
|
||||
getSender().tell(c, getSelf());
|
||||
|
||||
persistAsync(String.format("evt-%s-1", c), e -> {
|
||||
getSender().tell(e, getSelf());
|
||||
});
|
||||
persistAsync(String.format("evt-%s-2", c), e -> {
|
||||
getSender().tell(e, getSelf());
|
||||
});
|
||||
}
|
||||
|
||||
@Override public Receive createReceiveRecover() {
|
||||
return receiveBuilder().
|
||||
match(String.class, this::handleCommand).build();
|
||||
}
|
||||
|
||||
@Override public Receive createReceive() {
|
||||
return receiveBuilder().
|
||||
match(String.class, this::handleCommand).build();
|
||||
}
|
||||
}
|
||||
//#persist-async
|
||||
|
||||
public void usage() {
|
||||
final ActorSystem system = ActorSystem.create("example");
|
||||
//#persist-async-usage
|
||||
final ActorRef persistentActor = system.actorOf(Props.create(MyPersistentActor.class));
|
||||
persistentActor.tell("a", null);
|
||||
persistentActor.tell("b", null);
|
||||
|
||||
// possible order of received messages:
|
||||
// a
|
||||
// b
|
||||
// evt-a-1
|
||||
// evt-a-2
|
||||
// evt-b-1
|
||||
// evt-b-2
|
||||
//#persist-async-usage
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
static Object o10 = new Object() {
|
||||
//#defer
|
||||
class MyPersistentActor extends AbstractPersistentActor {
|
||||
|
||||
@Override public String persistenceId() {
|
||||
return "my-stable-persistence-id";
|
||||
}
|
||||
|
||||
private void handleCommand(String c) {
|
||||
persistAsync(String.format("evt-%s-1", c), e -> {
|
||||
getSender().tell(e, getSelf());
|
||||
});
|
||||
persistAsync(String.format("evt-%s-2", c), e -> {
|
||||
getSender().tell(e, getSelf());
|
||||
});
|
||||
|
||||
deferAsync(String.format("evt-%s-3", c), e -> {
|
||||
getSender().tell(e, getSelf());
|
||||
});
|
||||
}
|
||||
|
||||
@Override public Receive createReceiveRecover() {
|
||||
return receiveBuilder().
|
||||
match(String.class, this::handleCommand).build();
|
||||
}
|
||||
|
||||
@Override public Receive createReceive() {
|
||||
return receiveBuilder().
|
||||
match(String.class, this::handleCommand).build();
|
||||
}
|
||||
}
|
||||
//#defer
|
||||
|
||||
public void usage() {
|
||||
final ActorSystem system = ActorSystem.create("example");
|
||||
final ActorRef sender = null; // your imaginary sender here
|
||||
//#defer-caller
|
||||
final ActorRef persistentActor = system.actorOf(Props.create(MyPersistentActor.class));
|
||||
persistentActor.tell("a", sender);
|
||||
persistentActor.tell("b", sender);
|
||||
|
||||
// order of received messages:
|
||||
// a
|
||||
// b
|
||||
// evt-a-1
|
||||
// evt-a-2
|
||||
// evt-a-3
|
||||
// evt-b-1
|
||||
// evt-b-2
|
||||
// evt-b-3
|
||||
//#defer-caller
|
||||
}
|
||||
};
|
||||
|
||||
static Object o100 = new Object() {
|
||||
//#defer-with-persist
|
||||
class MyPersistentActor extends AbstractPersistentActor {
|
||||
|
||||
@Override public String persistenceId() {
|
||||
return "my-stable-persistence-id";
|
||||
}
|
||||
|
||||
private void handleCommand(String c) {
|
||||
persist(String.format("evt-%s-1", c), e -> {
|
||||
sender().tell(e, self());
|
||||
});
|
||||
persist(String.format("evt-%s-2", c), e -> {
|
||||
sender().tell(e, self());
|
||||
});
|
||||
|
||||
deferAsync(String.format("evt-%s-3", c), e -> {
|
||||
sender().tell(e, self());
|
||||
});
|
||||
}
|
||||
|
||||
@Override public Receive createReceiveRecover() {
|
||||
return receiveBuilder().
|
||||
match(String.class, this::handleCommand).build();
|
||||
}
|
||||
|
||||
@Override public Receive createReceive() {
|
||||
return receiveBuilder().
|
||||
match(String.class, this::handleCommand).build();
|
||||
}
|
||||
}
|
||||
//#defer-with-persist
|
||||
|
||||
};
|
||||
|
||||
static Object o11 = new Object() {
|
||||
|
||||
class MyPersistentActor extends AbstractPersistentActor {
|
||||
@Override
|
||||
public String persistenceId() {
|
||||
return "my-stable-persistence-id";
|
||||
}
|
||||
|
||||
@Override public Receive createReceive() {
|
||||
return receiveBuilder().matchAny(event -> {}).build();
|
||||
}
|
||||
|
||||
//#nested-persist-persist
|
||||
@Override public Receive createReceiveRecover() {
|
||||
final Procedure<String> replyToSender = event -> getSender().tell(event, getSelf());
|
||||
|
||||
return receiveBuilder()
|
||||
.match(String.class, msg -> {
|
||||
persist(String.format("%s-outer-1", msg), event -> {
|
||||
getSender().tell(event, getSelf());
|
||||
persist(String.format("%s-inner-1", event), replyToSender);
|
||||
});
|
||||
|
||||
persist(String.format("%s-outer-2", msg), event -> {
|
||||
getSender().tell(event, getSelf());
|
||||
persist(String.format("%s-inner-2", event), replyToSender);
|
||||
});
|
||||
})
|
||||
.build();
|
||||
}
|
||||
//#nested-persist-persist
|
||||
|
||||
void usage(ActorRef persistentActor) {
|
||||
//#nested-persist-persist-caller
|
||||
persistentActor.tell("a", ActorRef.noSender());
|
||||
persistentActor.tell("b", ActorRef.noSender());
|
||||
|
||||
// order of received messages:
|
||||
// a
|
||||
// a-outer-1
|
||||
// a-outer-2
|
||||
// a-inner-1
|
||||
// a-inner-2
|
||||
// and only then process "b"
|
||||
// b
|
||||
// b-outer-1
|
||||
// b-outer-2
|
||||
// b-inner-1
|
||||
// b-inner-2
|
||||
|
||||
//#nested-persist-persist-caller
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
class MyPersistAsyncActor extends AbstractPersistentActor {
|
||||
@Override
|
||||
public String persistenceId() {
|
||||
return "my-stable-persistence-id";
|
||||
}
|
||||
|
||||
@Override
|
||||
public Receive createReceiveRecover() {
|
||||
return receiveBuilder().matchAny(event -> {}).build();
|
||||
}
|
||||
|
||||
//#nested-persistAsync-persistAsync
|
||||
@Override
|
||||
public Receive createReceive() {
|
||||
final Procedure<String> replyToSender = event -> getSender().tell(event, getSelf());
|
||||
|
||||
return receiveBuilder()
|
||||
.match(String.class, msg -> {
|
||||
persistAsync(String.format("%s-outer-1", msg ), event -> {
|
||||
getSender().tell(event, getSelf());
|
||||
persistAsync(String.format("%s-inner-1", event), replyToSender);
|
||||
});
|
||||
|
||||
persistAsync(String.format("%s-outer-2", msg ), event -> {
|
||||
getSender().tell(event, getSelf());
|
||||
persistAsync(String.format("%s-inner-1", event), replyToSender);
|
||||
});
|
||||
})
|
||||
.build();
|
||||
}
|
||||
//#nested-persistAsync-persistAsync
|
||||
|
||||
void usage(ActorRef persistentActor) {
|
||||
//#nested-persistAsync-persistAsync-caller
|
||||
persistentActor.tell("a", getSelf());
|
||||
persistentActor.tell("b", getSelf());
|
||||
|
||||
// order of received messages:
|
||||
// a
|
||||
// b
|
||||
// a-outer-1
|
||||
// a-outer-2
|
||||
// b-outer-1
|
||||
// b-outer-2
|
||||
// a-inner-1
|
||||
// a-inner-2
|
||||
// b-inner-1
|
||||
// b-inner-2
|
||||
|
||||
// which can be seen as the following causal relationship:
|
||||
// a -> a-outer-1 -> a-outer-2 -> a-inner-1 -> a-inner-2
|
||||
// b -> b-outer-1 -> b-outer-2 -> b-inner-1 -> b-inner-2
|
||||
|
||||
//#nested-persistAsync-persistAsync-caller
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
static Object o14 = new Object() {
|
||||
//#safe-shutdown
|
||||
final class Shutdown {
|
||||
}
|
||||
|
||||
class MyPersistentActor extends AbstractPersistentActor {
|
||||
@Override
|
||||
public String persistenceId() {
|
||||
return "some-persistence-id";
|
||||
}
|
||||
|
||||
@Override
|
||||
public Receive createReceive() {
|
||||
return receiveBuilder()
|
||||
.match(Shutdown.class, shutdown -> {
|
||||
getContext().stop(getSelf());
|
||||
})
|
||||
.match(String.class, msg -> {
|
||||
System.out.println(msg);
|
||||
persist("handle-" + msg, e -> System.out.println(e));
|
||||
})
|
||||
.build();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Receive createReceiveRecover() {
|
||||
return receiveBuilder().matchAny(any -> {}).build();
|
||||
}
|
||||
|
||||
}
|
||||
//#safe-shutdown
|
||||
|
||||
|
||||
public void usage() {
|
||||
final ActorSystem system = ActorSystem.create("example");
|
||||
final ActorRef persistentActor = system.actorOf(Props.create(MyPersistentActor.class));
|
||||
//#safe-shutdown-example-bad
|
||||
// UN-SAFE, due to PersistentActor's command stashing:
|
||||
persistentActor.tell("a", ActorRef.noSender());
|
||||
persistentActor.tell("b", ActorRef.noSender());
|
||||
persistentActor.tell(PoisonPill.getInstance(), ActorRef.noSender());
|
||||
// order of received messages:
|
||||
// a
|
||||
// # b arrives at mailbox, stashing; internal-stash = [b]
|
||||
// # PoisonPill arrives at mailbox, stashing; internal-stash = [b, Shutdown]
|
||||
// PoisonPill is an AutoReceivedMessage, is handled automatically
|
||||
// !! stop !!
|
||||
// Actor is stopped without handling `b` nor the `a` handler!
|
||||
//#safe-shutdown-example-bad
|
||||
|
||||
//#safe-shutdown-example-good
|
||||
// SAFE:
|
||||
persistentActor.tell("a", ActorRef.noSender());
|
||||
persistentActor.tell("b", ActorRef.noSender());
|
||||
persistentActor.tell(new Shutdown(), ActorRef.noSender());
|
||||
// order of received messages:
|
||||
// a
|
||||
// # b arrives at mailbox, stashing; internal-stash = [b]
|
||||
// # Shutdown arrives at mailbox, stashing; internal-stash = [b, Shutdown]
|
||||
// handle-a
|
||||
// # unstashing; internal-stash = [Shutdown]
|
||||
// b
|
||||
// handle-b
|
||||
// # unstashing; internal-stash = []
|
||||
// Shutdown
|
||||
// -- stop --
|
||||
//#safe-shutdown-example-good
|
||||
}
|
||||
};
|
||||
}
|
||||
|
|
@ -0,0 +1,200 @@
|
|||
/**
|
||||
* Copyright (C) 2009-2017 Lightbend Inc. <http://www.lightbend.com>
|
||||
*/
|
||||
|
||||
package jdocs.persistence;
|
||||
|
||||
//#plugin-imports
|
||||
import akka.dispatch.Futures;
|
||||
import akka.persistence.*;
|
||||
import akka.persistence.journal.japi.*;
|
||||
import akka.persistence.snapshot.japi.*;
|
||||
//#plugin-imports
|
||||
|
||||
import akka.actor.*;
|
||||
import akka.persistence.journal.leveldb.SharedLeveldbJournal;
|
||||
import akka.persistence.journal.leveldb.SharedLeveldbStore;
|
||||
|
||||
import com.typesafe.config.Config;
|
||||
import com.typesafe.config.ConfigFactory;
|
||||
import java.io.File;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import scala.concurrent.Future;
|
||||
import java.util.function.Consumer;
|
||||
import org.iq80.leveldb.util.FileUtils;
|
||||
import java.util.Optional;
|
||||
|
||||
import akka.persistence.japi.journal.JavaJournalSpec;
|
||||
import akka.persistence.japi.snapshot.JavaSnapshotStoreSpec;
|
||||
|
||||
|
||||
public class LambdaPersistencePluginDocTest {
|
||||
|
||||
|
||||
static Object o1 = new Object() {
|
||||
final ActorSystem system = null;
|
||||
//#shared-store-creation
|
||||
final ActorRef store = system.actorOf(Props.create(SharedLeveldbStore.class), "store");
|
||||
//#shared-store-creation
|
||||
|
||||
//#shared-store-usage
|
||||
class SharedStorageUsage extends AbstractActor {
|
||||
@Override
|
||||
public void preStart() throws Exception {
|
||||
String path = "akka.tcp://example@127.0.0.1:2552/user/store";
|
||||
ActorSelection selection = getContext().actorSelection(path);
|
||||
selection.tell(new Identify(1), getSelf());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Receive createReceive() {
|
||||
return receiveBuilder()
|
||||
.match(ActorIdentity.class, ai -> {
|
||||
if (ai.correlationId().equals(1)) {
|
||||
Optional<ActorRef> store = ai.getActorRef();
|
||||
if (store.isPresent()) {
|
||||
SharedLeveldbJournal.setStore(store.get(), getContext().getSystem());
|
||||
} else {
|
||||
throw new RuntimeException("Couldn't identify store");
|
||||
}
|
||||
}
|
||||
})
|
||||
.build();
|
||||
}
|
||||
}
|
||||
//#shared-store-usage
|
||||
};
|
||||
|
||||
class MySnapshotStore extends SnapshotStore {
|
||||
@Override
|
||||
public Future<Optional<SelectedSnapshot>> doLoadAsync(String persistenceId, SnapshotSelectionCriteria criteria) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Future<Void> doSaveAsync(SnapshotMetadata metadata, Object snapshot) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Future<Void> doDeleteAsync(SnapshotMetadata metadata) {
|
||||
return Futures.successful(null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Future<Void> doDeleteAsync(String persistenceId, SnapshotSelectionCriteria criteria) {
|
||||
return Futures.successful(null);
|
||||
}
|
||||
}
|
||||
|
||||
class MyAsyncJournal extends AsyncWriteJournal {
|
||||
//#sync-journal-plugin-api
|
||||
@Override
|
||||
public Future<Iterable<Optional<Exception>>> doAsyncWriteMessages(
|
||||
Iterable<AtomicWrite> messages) {
|
||||
try {
|
||||
Iterable<Optional<Exception>> result = new ArrayList<Optional<Exception>>();
|
||||
// blocking call here...
|
||||
// result.add(..)
|
||||
return Futures.successful(result);
|
||||
} catch (Exception e) {
|
||||
return Futures.failed(e);
|
||||
}
|
||||
}
|
||||
//#sync-journal-plugin-api
|
||||
|
||||
@Override
|
||||
public Future<Void> doAsyncDeleteMessagesTo(String persistenceId, long toSequenceNr) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Future<Void> doAsyncReplayMessages(String persistenceId, long fromSequenceNr,
|
||||
long toSequenceNr,
|
||||
long max,
|
||||
Consumer<PersistentRepr> replayCallback) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Future<Long> doAsyncReadHighestSequenceNr(String persistenceId, long fromSequenceNr) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
static Object o2 = new Object() {
|
||||
//#journal-tck-java
|
||||
class MyJournalSpecTest extends JavaJournalSpec {
|
||||
|
||||
public MyJournalSpecTest() {
|
||||
super(ConfigFactory.parseString(
|
||||
"persistence.journal.plugin = " +
|
||||
"\"akka.persistence.journal.leveldb-shared\""));
|
||||
}
|
||||
|
||||
@Override
|
||||
public CapabilityFlag supportsRejectingNonSerializableObjects() {
|
||||
return CapabilityFlag.off();
|
||||
}
|
||||
}
|
||||
//#journal-tck-java
|
||||
};
|
||||
|
||||
static Object o3 = new Object() {
|
||||
//#snapshot-store-tck-java
|
||||
class MySnapshotStoreTest extends JavaSnapshotStoreSpec {
|
||||
|
||||
public MySnapshotStoreTest() {
|
||||
super(ConfigFactory.parseString(
|
||||
"akka.persistence.snapshot-store.plugin = " +
|
||||
"\"akka.persistence.snapshot-store.local\""));
|
||||
}
|
||||
}
|
||||
//#snapshot-store-tck-java
|
||||
};
|
||||
|
||||
static Object o4 = new Object() {
|
||||
//#journal-tck-before-after-java
|
||||
class MyJournalSpecTest extends JavaJournalSpec {
|
||||
|
||||
List<File> storageLocations = new ArrayList<File>();
|
||||
|
||||
public MyJournalSpecTest() {
|
||||
super(ConfigFactory.parseString(
|
||||
"persistence.journal.plugin = " +
|
||||
"\"akka.persistence.journal.leveldb-shared\""));
|
||||
|
||||
Config config = system().settings().config();
|
||||
storageLocations.add(new File(
|
||||
config.getString("akka.persistence.journal.leveldb.dir")));
|
||||
storageLocations.add(new File(
|
||||
config.getString("akka.persistence.snapshot-store.local.dir")));
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public CapabilityFlag supportsRejectingNonSerializableObjects() {
|
||||
return CapabilityFlag.on();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void beforeAll() {
|
||||
for (File storageLocation : storageLocations) {
|
||||
FileUtils.deleteRecursively(storageLocation);
|
||||
}
|
||||
super.beforeAll();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void afterAll() {
|
||||
super.afterAll();
|
||||
for (File storageLocation : storageLocations) {
|
||||
FileUtils.deleteRecursively(storageLocation);
|
||||
}
|
||||
}
|
||||
}
|
||||
//#journal-tck-before-after-java
|
||||
};
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,32 @@
|
|||
/*
|
||||
* Copyright (C) 2015-2017 Lightbend Inc. <http://www.lightbend.com>
|
||||
*/
|
||||
|
||||
package jdocs.persistence;
|
||||
|
||||
import akka.persistence.journal.EventAdapter;
|
||||
import akka.persistence.journal.EventSeq;
|
||||
|
||||
public class PersistenceEventAdapterDocTest {
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
static
|
||||
//#identity-event-adapter
|
||||
class MyEventAdapter implements EventAdapter {
|
||||
@Override
|
||||
public String manifest(Object event) {
|
||||
return ""; // if no manifest needed, return ""
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object toJournal(Object event) {
|
||||
return event; // identity
|
||||
}
|
||||
|
||||
@Override
|
||||
public EventSeq fromJournal(Object event, String manifest) {
|
||||
return EventSeq.single(event); // identity
|
||||
}
|
||||
}
|
||||
//#identity-event-adapter
|
||||
}
|
||||
|
|
@ -0,0 +1,31 @@
|
|||
/**
|
||||
* Copyright (C) 2009-2017 Lightbend Inc. <http://www.lightbend.com>
|
||||
*/
|
||||
|
||||
package jdocs.persistence;
|
||||
|
||||
import akka.persistence.UntypedPersistentActor;
|
||||
|
||||
public class PersistenceMultiDocTest {
|
||||
|
||||
//#default-plugins
|
||||
abstract class ActorWithDefaultPlugins extends UntypedPersistentActor {
|
||||
@Override
|
||||
public String persistenceId() { return "123"; }
|
||||
}
|
||||
//#default-plugins
|
||||
|
||||
//#override-plugins
|
||||
abstract class ActorWithOverridePlugins extends UntypedPersistentActor {
|
||||
@Override
|
||||
public String persistenceId() { return "123"; }
|
||||
// Absolute path to the journal plugin configuration entry in the `reference.conf`
|
||||
@Override
|
||||
public String journalPluginId() { return "akka.persistence.chronicle.journal"; }
|
||||
// Absolute path to the snapshot store plugin configuration entry in the `reference.conf`
|
||||
@Override
|
||||
public String snapshotPluginId() { return "akka.persistence.chronicle.snapshot-store"; }
|
||||
}
|
||||
//#override-plugins
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,476 @@
|
|||
/**
|
||||
* Copyright (C) 2009-2017 Lightbend Inc. <http://www.lightbend.com>
|
||||
*/
|
||||
|
||||
package jdocs.persistence;
|
||||
|
||||
import static akka.pattern.PatternsCS.ask;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
import akka.NotUsed;
|
||||
import akka.persistence.query.Sequence;
|
||||
import akka.persistence.query.Offset;
|
||||
import com.typesafe.config.Config;
|
||||
|
||||
import akka.actor.*;
|
||||
import akka.persistence.query.*;
|
||||
import akka.stream.ActorMaterializer;
|
||||
import akka.stream.javadsl.Sink;
|
||||
import akka.stream.javadsl.Source;
|
||||
import akka.util.Timeout;
|
||||
|
||||
import docs.persistence.query.MyEventsByTagPublisher;
|
||||
import org.reactivestreams.Subscriber;
|
||||
import scala.concurrent.duration.FiniteDuration;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CompletionStage;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
public class PersistenceQueryDocTest {
|
||||
|
||||
final ActorSystem system = ActorSystem.create();
|
||||
final ActorMaterializer mat = ActorMaterializer.create(system);
|
||||
|
||||
static
|
||||
//#advanced-journal-query-types
|
||||
public class RichEvent {
|
||||
public final Set<String >tags;
|
||||
public final Object payload;
|
||||
|
||||
public RichEvent(Set<String> tags, Object payload) {
|
||||
this.tags = tags;
|
||||
this.payload = payload;
|
||||
}
|
||||
}
|
||||
//#advanced-journal-query-types
|
||||
|
||||
static
|
||||
//#advanced-journal-query-types
|
||||
// a plugin can provide:
|
||||
public final class QueryMetadata{
|
||||
public final boolean deterministicOrder;
|
||||
public final boolean infinite;
|
||||
|
||||
public QueryMetadata(boolean deterministicOrder, boolean infinite) {
|
||||
this.deterministicOrder = deterministicOrder;
|
||||
this.infinite = infinite;
|
||||
}
|
||||
}
|
||||
//#advanced-journal-query-types
|
||||
|
||||
static
|
||||
//#my-read-journal
|
||||
public class MyReadJournalProvider implements ReadJournalProvider {
|
||||
private final MyJavadslReadJournal javadslReadJournal;
|
||||
|
||||
public MyReadJournalProvider(ExtendedActorSystem system, Config config) {
|
||||
this.javadslReadJournal = new MyJavadslReadJournal(system, config);
|
||||
}
|
||||
|
||||
@Override
|
||||
public MyScaladslReadJournal scaladslReadJournal() {
|
||||
return new MyScaladslReadJournal(javadslReadJournal);
|
||||
}
|
||||
|
||||
@Override
|
||||
public MyJavadslReadJournal javadslReadJournal() {
|
||||
return this.javadslReadJournal;
|
||||
}
|
||||
}
|
||||
//#my-read-journal
|
||||
|
||||
static
|
||||
//#my-read-journal
|
||||
public class MyJavadslReadJournal implements
|
||||
akka.persistence.query.javadsl.ReadJournal,
|
||||
akka.persistence.query.javadsl.EventsByTagQuery,
|
||||
akka.persistence.query.javadsl.EventsByPersistenceIdQuery,
|
||||
akka.persistence.query.javadsl.PersistenceIdsQuery,
|
||||
akka.persistence.query.javadsl.CurrentPersistenceIdsQuery {
|
||||
|
||||
private final FiniteDuration refreshInterval;
|
||||
|
||||
public MyJavadslReadJournal(ExtendedActorSystem system, Config config) {
|
||||
refreshInterval =
|
||||
FiniteDuration.create(config.getDuration("refresh-interval",
|
||||
TimeUnit.MILLISECONDS), TimeUnit.MILLISECONDS);
|
||||
}
|
||||
|
||||
/**
|
||||
* You can use `NoOffset` to retrieve all events with a given tag or retrieve a subset of all
|
||||
* events by specifying a `Sequence` `offset`. The `offset` corresponds to an ordered sequence number for
|
||||
* the specific tag. Note that the corresponding offset of each event is provided in the
|
||||
* [[akka.persistence.query.EventEnvelope]], which makes it possible to resume the
|
||||
* stream at a later point from a given offset.
|
||||
*
|
||||
* The `offset` is exclusive, i.e. the event with the exact same sequence number will not be included
|
||||
* in the returned stream. This means that you can use the offset that is returned in `EventEnvelope`
|
||||
* as the `offset` parameter in a subsequent query.
|
||||
*/
|
||||
@Override
|
||||
public Source<EventEnvelope, NotUsed> eventsByTag(String tag, Offset offset) {
|
||||
if(offset instanceof Sequence){
|
||||
Sequence sequenceOffset = (Sequence) offset;
|
||||
final Props props = MyEventsByTagPublisher.props(tag, sequenceOffset.value(), refreshInterval);
|
||||
return Source.<EventEnvelope>actorPublisher(props).
|
||||
mapMaterializedValue(m -> NotUsed.getInstance());
|
||||
} else if (offset == NoOffset.getInstance())
|
||||
return eventsByTag(tag, Offset.sequence(0L)); //recursive
|
||||
else
|
||||
throw new IllegalArgumentException("MyJavadslReadJournal does not support " + offset.getClass().getName() + " offsets");
|
||||
}
|
||||
|
||||
@Override
|
||||
public Source<EventEnvelope, NotUsed> eventsByPersistenceId(String persistenceId,
|
||||
long fromSequenceNr, long toSequenceNr) {
|
||||
// implement in a similar way as eventsByTag
|
||||
throw new UnsupportedOperationException("Not implemented yet");
|
||||
}
|
||||
|
||||
@Override
|
||||
public Source<String, NotUsed> persistenceIds() {
|
||||
// implement in a similar way as eventsByTag
|
||||
throw new UnsupportedOperationException("Not implemented yet");
|
||||
}
|
||||
|
||||
@Override
|
||||
public Source<String, NotUsed> currentPersistenceIds() {
|
||||
// implement in a similar way as eventsByTag
|
||||
throw new UnsupportedOperationException("Not implemented yet");
|
||||
}
|
||||
|
||||
// possibility to add more plugin specific queries
|
||||
|
||||
//#advanced-journal-query-definition
|
||||
public Source<RichEvent, QueryMetadata> byTagsWithMeta(Set<String> tags) {
|
||||
//#advanced-journal-query-definition
|
||||
// implement in a similar way as eventsByTag
|
||||
throw new UnsupportedOperationException("Not implemented yet");
|
||||
}
|
||||
|
||||
}
|
||||
//#my-read-journal
|
||||
|
||||
static
|
||||
//#my-read-journal
|
||||
public class MyScaladslReadJournal implements
|
||||
akka.persistence.query.scaladsl.ReadJournal,
|
||||
akka.persistence.query.scaladsl.EventsByTagQuery,
|
||||
akka.persistence.query.scaladsl.EventsByPersistenceIdQuery,
|
||||
akka.persistence.query.scaladsl.PersistenceIdsQuery,
|
||||
akka.persistence.query.scaladsl.CurrentPersistenceIdsQuery {
|
||||
|
||||
private final MyJavadslReadJournal javadslReadJournal;
|
||||
|
||||
public MyScaladslReadJournal(MyJavadslReadJournal javadslReadJournal) {
|
||||
this.javadslReadJournal = javadslReadJournal;
|
||||
}
|
||||
|
||||
@Override
|
||||
public akka.stream.scaladsl.Source<EventEnvelope, NotUsed> eventsByTag(
|
||||
String tag, akka.persistence.query.Offset offset) {
|
||||
return javadslReadJournal.eventsByTag(tag, offset).asScala();
|
||||
}
|
||||
|
||||
@Override
|
||||
public akka.stream.scaladsl.Source<EventEnvelope, NotUsed> eventsByPersistenceId(
|
||||
String persistenceId, long fromSequenceNr, long toSequenceNr) {
|
||||
return javadslReadJournal.eventsByPersistenceId(persistenceId, fromSequenceNr,
|
||||
toSequenceNr).asScala();
|
||||
}
|
||||
|
||||
@Override
|
||||
public akka.stream.scaladsl.Source<String, NotUsed> persistenceIds() {
|
||||
return javadslReadJournal.persistenceIds().asScala();
|
||||
}
|
||||
|
||||
@Override
|
||||
public akka.stream.scaladsl.Source<String, NotUsed> currentPersistenceIds() {
|
||||
return javadslReadJournal.currentPersistenceIds().asScala();
|
||||
}
|
||||
|
||||
// possibility to add more plugin specific queries
|
||||
|
||||
public akka.stream.scaladsl.Source<RichEvent, QueryMetadata> byTagsWithMeta(
|
||||
scala.collection.Set<String> tags) {
|
||||
Set<String> jTags = scala.collection.JavaConversions.setAsJavaSet(tags);
|
||||
return javadslReadJournal.byTagsWithMeta(jTags).asScala();
|
||||
}
|
||||
|
||||
}
|
||||
//#my-read-journal
|
||||
|
||||
void demonstrateBasicUsage() {
|
||||
final ActorSystem system = ActorSystem.create();
|
||||
|
||||
//#basic-usage
|
||||
// obtain read journal by plugin id
|
||||
final MyJavadslReadJournal readJournal =
|
||||
PersistenceQuery.get(system).getReadJournalFor(MyJavadslReadJournal.class,
|
||||
"akka.persistence.query.my-read-journal");
|
||||
|
||||
// issue query to journal
|
||||
Source<EventEnvelope, NotUsed> source =
|
||||
readJournal.eventsByPersistenceId("user-1337", 0, Long.MAX_VALUE);
|
||||
|
||||
// materialize stream, consuming events
|
||||
ActorMaterializer mat = ActorMaterializer.create(system);
|
||||
source.runForeach(event -> System.out.println("Event: " + event), mat);
|
||||
//#basic-usage
|
||||
}
|
||||
|
||||
void demonstrateAllPersistenceIdsLive() {
|
||||
final MyJavadslReadJournal readJournal =
|
||||
PersistenceQuery.get(system).getReadJournalFor(MyJavadslReadJournal.class,
|
||||
"akka.persistence.query.my-read-journal");
|
||||
|
||||
//#all-persistence-ids-live
|
||||
readJournal.persistenceIds();
|
||||
//#all-persistence-ids-live
|
||||
}
|
||||
|
||||
void demonstrateNoRefresh() {
|
||||
final ActorSystem system = ActorSystem.create();
|
||||
|
||||
final MyJavadslReadJournal readJournal =
|
||||
PersistenceQuery.get(system).getReadJournalFor(MyJavadslReadJournal.class,
|
||||
"akka.persistence.query.my-read-journal");
|
||||
|
||||
//#all-persistence-ids-snap
|
||||
readJournal.currentPersistenceIds();
|
||||
//#all-persistence-ids-snap
|
||||
}
|
||||
|
||||
void demonstrateRefresh() {
|
||||
final ActorSystem system = ActorSystem.create();
|
||||
|
||||
final MyJavadslReadJournal readJournal =
|
||||
PersistenceQuery.get(system).getReadJournalFor(MyJavadslReadJournal.class,
|
||||
"akka.persistence.query.my-read-journal");
|
||||
|
||||
//#events-by-persistent-id
|
||||
readJournal.eventsByPersistenceId("user-us-1337", 0L, Long.MAX_VALUE);
|
||||
//#events-by-persistent-id
|
||||
}
|
||||
|
||||
void demonstrateEventsByTag() {
|
||||
final ActorSystem system = ActorSystem.create();
|
||||
final ActorMaterializer mat = ActorMaterializer.create(system);
|
||||
|
||||
final MyJavadslReadJournal readJournal =
|
||||
PersistenceQuery.get(system).getReadJournalFor(MyJavadslReadJournal.class,
|
||||
"akka.persistence.query.my-read-journal");
|
||||
|
||||
//#events-by-tag
|
||||
// assuming journal is able to work with numeric offsets we can:
|
||||
final Source<EventEnvelope, NotUsed> blueThings =
|
||||
readJournal.eventsByTag("blue", new Sequence(0L));
|
||||
|
||||
// find top 10 blue things:
|
||||
final CompletionStage<List<Object>> top10BlueThings =
|
||||
blueThings
|
||||
.map(EventEnvelope::event)
|
||||
.take(10) // cancels the query stream after pulling 10 elements
|
||||
.runFold(new ArrayList<>(10), (acc, e) -> {
|
||||
acc.add(e);
|
||||
return acc;
|
||||
}, mat);
|
||||
|
||||
// start another query, from the known offset
|
||||
Source<EventEnvelope, NotUsed> blue = readJournal.eventsByTag("blue", new Sequence(10));
|
||||
//#events-by-tag
|
||||
}
|
||||
|
||||
|
||||
void demonstrateMaterializedQueryValues() {
|
||||
final ActorSystem system = ActorSystem.create();
|
||||
final ActorMaterializer mat = ActorMaterializer.create(system);
|
||||
|
||||
final MyJavadslReadJournal readJournal =
|
||||
PersistenceQuery.get(system).getReadJournalFor(MyJavadslReadJournal.class,
|
||||
"akka.persistence.query.my-read-journal");
|
||||
|
||||
//#advanced-journal-query-usage
|
||||
|
||||
Set<String> tags = new HashSet<String>();
|
||||
tags.add("red");
|
||||
tags.add("blue");
|
||||
final Source<RichEvent, QueryMetadata> events = readJournal.byTagsWithMeta(tags)
|
||||
.mapMaterializedValue(meta -> {
|
||||
System.out.println("The query is: " +
|
||||
"ordered deterministically: " + meta.deterministicOrder + " " +
|
||||
"infinite: " + meta.infinite);
|
||||
return meta;
|
||||
});
|
||||
|
||||
events.map(event -> {
|
||||
System.out.println("Event payload: " + event.payload);
|
||||
return event.payload;
|
||||
}).runWith(Sink.ignore(), mat);
|
||||
|
||||
|
||||
//#advanced-journal-query-usage
|
||||
}
|
||||
|
||||
class ReactiveStreamsCompatibleDBDriver {
|
||||
Subscriber<List<Object>> batchWriter() {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
void demonstrateWritingIntoDifferentStore() {
|
||||
final ActorSystem system = ActorSystem.create();
|
||||
final ActorMaterializer mat = ActorMaterializer.create(system);
|
||||
|
||||
final MyJavadslReadJournal readJournal =
|
||||
PersistenceQuery.get(system).getReadJournalFor(MyJavadslReadJournal.class,
|
||||
"akka.persistence.query.my-read-journal");
|
||||
|
||||
|
||||
//#projection-into-different-store-rs
|
||||
final ReactiveStreamsCompatibleDBDriver driver = new ReactiveStreamsCompatibleDBDriver();
|
||||
final Subscriber<List<Object>> dbBatchWriter = driver.batchWriter();
|
||||
|
||||
// Using an example (Reactive Streams) Database driver
|
||||
readJournal
|
||||
.eventsByPersistenceId("user-1337", 0L, Long.MAX_VALUE)
|
||||
.map(envelope -> envelope.event())
|
||||
.grouped(20) // batch inserts into groups of 20
|
||||
.runWith(Sink.fromSubscriber(dbBatchWriter), mat); // write batches to read-side database
|
||||
//#projection-into-different-store-rs
|
||||
}
|
||||
|
||||
//#projection-into-different-store-simple-classes
|
||||
class ExampleStore {
|
||||
CompletionStage<Void> save(Object any) {
|
||||
// ...
|
||||
//#projection-into-different-store-simple-classes
|
||||
return null;
|
||||
//#projection-into-different-store-simple-classes
|
||||
}
|
||||
}
|
||||
//#projection-into-different-store-simple-classes
|
||||
|
||||
void demonstrateWritingIntoDifferentStoreWithMapAsync() {
|
||||
final ActorSystem system = ActorSystem.create();
|
||||
final ActorMaterializer mat = ActorMaterializer.create(system);
|
||||
|
||||
final MyJavadslReadJournal readJournal =
|
||||
PersistenceQuery.get(system).getReadJournalFor(MyJavadslReadJournal.class,
|
||||
"akka.persistence.query.my-read-journal");
|
||||
|
||||
|
||||
//#projection-into-different-store-simple
|
||||
final ExampleStore store = new ExampleStore();
|
||||
|
||||
readJournal
|
||||
.eventsByTag("bid", new Sequence(0L))
|
||||
.mapAsync(1, store::save)
|
||||
.runWith(Sink.ignore(), mat);
|
||||
//#projection-into-different-store-simple
|
||||
}
|
||||
|
||||
//#projection-into-different-store
|
||||
class MyResumableProjection {
|
||||
private final String name;
|
||||
|
||||
public MyResumableProjection(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public CompletionStage<Long> saveProgress(Offset offset) {
|
||||
// ...
|
||||
//#projection-into-different-store
|
||||
return null;
|
||||
//#projection-into-different-store
|
||||
}
|
||||
public CompletionStage<Long> latestOffset() {
|
||||
// ...
|
||||
//#projection-into-different-store
|
||||
return null;
|
||||
//#projection-into-different-store
|
||||
}
|
||||
}
|
||||
//#projection-into-different-store
|
||||
|
||||
|
||||
void demonstrateWritingIntoDifferentStoreWithResumableProjections() throws Exception {
|
||||
final ActorSystem system = ActorSystem.create();
|
||||
final ActorMaterializer mat = ActorMaterializer.create(system);
|
||||
|
||||
final MyJavadslReadJournal readJournal =
|
||||
PersistenceQuery.get(system).getReadJournalFor(MyJavadslReadJournal.class,
|
||||
"akka.persistence.query.my-read-journal");
|
||||
|
||||
|
||||
//#projection-into-different-store-actor-run
|
||||
final Timeout timeout = Timeout.apply(3, TimeUnit.SECONDS);
|
||||
|
||||
final MyResumableProjection bidProjection = new MyResumableProjection("bid");
|
||||
|
||||
final Props writerProps = Props.create(TheOneWhoWritesToQueryJournal.class, "bid");
|
||||
final ActorRef writer = system.actorOf(writerProps, "bid-projection-writer");
|
||||
|
||||
long startFromOffset = bidProjection.latestOffset().toCompletableFuture().get(3, TimeUnit.SECONDS);
|
||||
|
||||
readJournal
|
||||
.eventsByTag("bid", new Sequence(startFromOffset))
|
||||
.mapAsync(8, envelope -> {
|
||||
final CompletionStage<Object> f = ask(writer, envelope.event(), timeout);
|
||||
return f.thenApplyAsync(in -> envelope.offset(), system.dispatcher());
|
||||
})
|
||||
.mapAsync(1, offset -> bidProjection.saveProgress(offset))
|
||||
.runWith(Sink.ignore(), mat);
|
||||
}
|
||||
|
||||
//#projection-into-different-store-actor-run
|
||||
|
||||
class ComplexState {
|
||||
|
||||
boolean readyToSave() {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
static class Record {
|
||||
static Record of(Object any) {
|
||||
return new Record();
|
||||
}
|
||||
}
|
||||
|
||||
//#projection-into-different-store-actor
|
||||
final class TheOneWhoWritesToQueryJournal extends AbstractActor {
|
||||
private final ExampleStore store;
|
||||
|
||||
private ComplexState state = new ComplexState();
|
||||
|
||||
public TheOneWhoWritesToQueryJournal() {
|
||||
store = new ExampleStore();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Receive createReceive() {
|
||||
return receiveBuilder()
|
||||
.matchAny(message -> {
|
||||
state = updateState(state, message);
|
||||
|
||||
// example saving logic that requires state to become ready:
|
||||
if (state.readyToSave())
|
||||
store.save(Record.of(state));
|
||||
|
||||
})
|
||||
.build();
|
||||
}
|
||||
|
||||
|
||||
ComplexState updateState(ComplexState state, Object msg) {
|
||||
// some complicated aggregation logic here ...
|
||||
return state;
|
||||
}
|
||||
}
|
||||
//#projection-into-different-store-actor
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,534 @@
|
|||
/**
|
||||
* Copyright (C) 2009-2017 Lightbend Inc. <http://www.lightbend.com>
|
||||
*/
|
||||
|
||||
package jdocs.persistence;
|
||||
|
||||
import docs.persistence.ExampleJsonMarshaller;
|
||||
import docs.persistence.proto.FlightAppModels;
|
||||
import java.nio.charset.Charset;
|
||||
import spray.json.JsObject;
|
||||
|
||||
import akka.persistence.journal.EventAdapter;
|
||||
import akka.persistence.journal.EventSeq;
|
||||
import akka.protobuf.InvalidProtocolBufferException;
|
||||
import akka.serialization.SerializerWithStringManifest;
|
||||
|
||||
public class PersistenceSchemaEvolutionDocTest {
|
||||
|
||||
static
|
||||
//#protobuf-read-optional-model
|
||||
public enum SeatType {
|
||||
Window("W"), Aisle("A"), Other("O"), Unknown("");
|
||||
|
||||
private final String code;
|
||||
|
||||
private SeatType(String code) {
|
||||
this.code = code;
|
||||
}
|
||||
|
||||
public static SeatType fromCode(String c) {
|
||||
if (Window.code.equals(c))
|
||||
return Window;
|
||||
else if (Aisle.code.equals(c))
|
||||
return Aisle;
|
||||
else if (Other.code.equals(c))
|
||||
return Other;
|
||||
else
|
||||
return Unknown;
|
||||
}
|
||||
}
|
||||
//#protobuf-read-optional-model
|
||||
|
||||
static
|
||||
//#protobuf-read-optional-model
|
||||
public class SeatReserved {
|
||||
public final String letter;
|
||||
public final int row;
|
||||
public final SeatType seatType;
|
||||
|
||||
public SeatReserved(String letter, int row, SeatType seatType) {
|
||||
this.letter = letter;
|
||||
this.row = row;
|
||||
this.seatType = seatType;
|
||||
}
|
||||
}
|
||||
//#protobuf-read-optional-model
|
||||
|
||||
static
|
||||
//#protobuf-read-optional
|
||||
/**
|
||||
* Example serializer impl which uses protocol buffers generated classes (proto.*)
|
||||
* to perform the to/from binary marshalling.
|
||||
*/
|
||||
public class AddedFieldsSerializerWithProtobuf extends SerializerWithStringManifest {
|
||||
@Override public int identifier() {
|
||||
return 67876;
|
||||
}
|
||||
|
||||
private final String seatReservedManifest = SeatReserved.class.getName();
|
||||
|
||||
@Override public String manifest(Object o){
|
||||
return o.getClass().getName();
|
||||
}
|
||||
|
||||
@Override public Object fromBinary(byte[] bytes, String manifest) {
|
||||
if (seatReservedManifest.equals(manifest)) {
|
||||
// use generated protobuf serializer
|
||||
try {
|
||||
return seatReserved(FlightAppModels.SeatReserved.parseFrom(bytes));
|
||||
} catch (InvalidProtocolBufferException e) {
|
||||
throw new IllegalArgumentException(e.getMessage());
|
||||
}
|
||||
} else {
|
||||
throw new IllegalArgumentException("Unable to handle manifest: " + manifest);
|
||||
}
|
||||
}
|
||||
|
||||
@Override public byte[] toBinary(Object o) {
|
||||
if (o instanceof SeatReserved) {
|
||||
SeatReserved s = (SeatReserved) o;
|
||||
return FlightAppModels.SeatReserved.newBuilder()
|
||||
.setRow(s.row)
|
||||
.setLetter(s.letter)
|
||||
.setSeatType(s.seatType.code)
|
||||
.build().toByteArray();
|
||||
|
||||
} else {
|
||||
throw new IllegalArgumentException("Unable to handle: " + o);
|
||||
}
|
||||
}
|
||||
|
||||
// -- fromBinary helpers --
|
||||
|
||||
private SeatReserved seatReserved(FlightAppModels.SeatReserved p) {
|
||||
return new SeatReserved(p.getLetter(), p.getRow(), seatType(p));
|
||||
}
|
||||
|
||||
// handle missing field by assigning "Unknown" value
|
||||
private SeatType seatType(FlightAppModels.SeatReserved p) {
|
||||
if (p.hasSeatType())
|
||||
return SeatType.fromCode(p.getSeatType());
|
||||
else
|
||||
return SeatType.Unknown;
|
||||
}
|
||||
|
||||
}
|
||||
//#protobuf-read-optional
|
||||
|
||||
|
||||
public static class RenamePlainJson {
|
||||
static
|
||||
//#rename-plain-json
|
||||
public class JsonRenamedFieldAdapter implements EventAdapter {
|
||||
// use your favorite json library
|
||||
private final ExampleJsonMarshaller marshaller = new ExampleJsonMarshaller();
|
||||
|
||||
private final String V1 = "v1";
|
||||
private final String V2 = "v2";
|
||||
|
||||
// this could be done independently for each event type
|
||||
@Override public String manifest(Object event) {
|
||||
return V2;
|
||||
}
|
||||
|
||||
@Override public JsObject toJournal(Object event) {
|
||||
return marshaller.toJson(event);
|
||||
}
|
||||
|
||||
@Override public EventSeq fromJournal(Object event, String manifest) {
|
||||
if (event instanceof JsObject) {
|
||||
JsObject json = (JsObject) event;
|
||||
if (V1.equals(manifest))
|
||||
json = rename(json, "code", "seatNr");
|
||||
return EventSeq.single(json);
|
||||
} else {
|
||||
throw new IllegalArgumentException("Can only work with JSON, was: " +
|
||||
event.getClass().getName());
|
||||
}
|
||||
}
|
||||
|
||||
private JsObject rename(JsObject json, String from, String to) {
|
||||
// use your favorite json library to rename the field
|
||||
JsObject renamed = json;
|
||||
return renamed;
|
||||
}
|
||||
|
||||
}
|
||||
//#rename-plain-json
|
||||
}
|
||||
|
||||
public static class SimplestCustomSerializer {
|
||||
|
||||
static
|
||||
//#simplest-custom-serializer-model
|
||||
public class Person {
|
||||
public final String name;
|
||||
public final String surname;
|
||||
public Person(String name, String surname) {
|
||||
this.name = name;
|
||||
this.surname = surname;
|
||||
}
|
||||
}
|
||||
//#simplest-custom-serializer-model
|
||||
|
||||
static
|
||||
//#simplest-custom-serializer
|
||||
/**
|
||||
* Simplest possible serializer, uses a string representation of the Person class.
|
||||
*
|
||||
* Usually a serializer like this would use a library like:
|
||||
* protobuf, kryo, avro, cap'n proto, flatbuffers, SBE or some other dedicated serializer backend
|
||||
* to perform the actual to/from bytes marshalling.
|
||||
*/
|
||||
public class SimplestPossiblePersonSerializer extends SerializerWithStringManifest {
|
||||
private final Charset utf8 = Charset.forName("UTF-8");
|
||||
|
||||
private final String personManifest = Person.class.getName();
|
||||
|
||||
// unique identifier of the serializer
|
||||
@Override public int identifier() {
|
||||
return 1234567;
|
||||
}
|
||||
|
||||
// extract manifest to be stored together with serialized object
|
||||
@Override public String manifest(Object o) {
|
||||
return o.getClass().getName();
|
||||
}
|
||||
|
||||
// serialize the object
|
||||
@Override public byte[] toBinary(Object obj) {
|
||||
if (obj instanceof Person) {
|
||||
Person p = (Person) obj;
|
||||
return (p.name + "|" + p.surname).getBytes(utf8);
|
||||
} else {
|
||||
throw new IllegalArgumentException(
|
||||
"Unable to serialize to bytes, clazz was: " + obj.getClass().getName());
|
||||
}
|
||||
}
|
||||
|
||||
// deserialize the object, using the manifest to indicate which logic to apply
|
||||
@Override public Object fromBinary(byte[] bytes, String manifest) {
|
||||
if (personManifest.equals(manifest)) {
|
||||
String nameAndSurname = new String(bytes, utf8);
|
||||
String[] parts = nameAndSurname.split("[|]");
|
||||
return new Person(parts[0], parts[1]);
|
||||
} else {
|
||||
throw new IllegalArgumentException(
|
||||
"Unable to deserialize from bytes, manifest was: " + manifest +
|
||||
"! Bytes length: " + bytes.length);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
//#simplest-custom-serializer
|
||||
}
|
||||
|
||||
|
||||
public static class SamplePayload {
|
||||
private final Object payload;
|
||||
|
||||
public SamplePayload(Object payload) {
|
||||
this.payload = payload;
|
||||
}
|
||||
|
||||
public Object getPayload() {
|
||||
return payload;
|
||||
}
|
||||
}
|
||||
|
||||
//#split-events-during-recovery
|
||||
interface V1 {};
|
||||
interface V2 {}
|
||||
|
||||
//#split-events-during-recovery
|
||||
static
|
||||
//#split-events-during-recovery
|
||||
// V1 event:
|
||||
public class UserDetailsChanged implements V1 {
|
||||
public final String name;
|
||||
public final String address;
|
||||
public UserDetailsChanged(String name, String address) {
|
||||
this.name = name;
|
||||
this.address = address;
|
||||
}
|
||||
}
|
||||
|
||||
//#split-events-during-recovery
|
||||
static
|
||||
//#split-events-during-recovery
|
||||
// corresponding V2 events:
|
||||
public class UserNameChanged implements V2 {
|
||||
public final String name;
|
||||
|
||||
public UserNameChanged(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
}
|
||||
//#split-events-during-recovery
|
||||
static
|
||||
//#split-events-during-recovery
|
||||
public class UserAddressChanged implements V2 {
|
||||
public final String address;
|
||||
|
||||
public UserAddressChanged(String address) {
|
||||
this.address = address;
|
||||
}
|
||||
}
|
||||
|
||||
//#split-events-during-recovery
|
||||
static
|
||||
//#split-events-during-recovery
|
||||
// event splitting adapter:
|
||||
public class UserEventsAdapter implements EventAdapter {
|
||||
@Override public String manifest(Object event) {
|
||||
return "";
|
||||
}
|
||||
|
||||
@Override public EventSeq fromJournal(Object event, String manifest) {
|
||||
if (event instanceof UserDetailsChanged) {
|
||||
UserDetailsChanged c = (UserDetailsChanged) event;
|
||||
if (c.name == null)
|
||||
return EventSeq.single(new UserAddressChanged(c.address));
|
||||
else if (c.address == null)
|
||||
return EventSeq.single(new UserNameChanged(c.name));
|
||||
else
|
||||
return EventSeq.create(
|
||||
new UserNameChanged(c.name),
|
||||
new UserAddressChanged(c.address));
|
||||
} else {
|
||||
return EventSeq.single(event);
|
||||
}
|
||||
}
|
||||
|
||||
@Override public Object toJournal(Object event) {
|
||||
return event;
|
||||
}
|
||||
}
|
||||
//#split-events-during-recovery
|
||||
|
||||
|
||||
static public class CustomerBlinked {
|
||||
public final long customerId;
|
||||
|
||||
public CustomerBlinked(long customerId) {
|
||||
this.customerId = customerId;
|
||||
}
|
||||
}
|
||||
|
||||
static
|
||||
//#string-serializer-skip-deleved-event-by-manifest
|
||||
public class EventDeserializationSkipped {
|
||||
public static EventDeserializationSkipped instance =
|
||||
new EventDeserializationSkipped();
|
||||
|
||||
private EventDeserializationSkipped() {
|
||||
}
|
||||
}
|
||||
|
||||
//#string-serializer-skip-deleved-event-by-manifest
|
||||
static
|
||||
//#string-serializer-skip-deleved-event-by-manifest
|
||||
public class RemovedEventsAwareSerializer extends SerializerWithStringManifest {
|
||||
private final Charset utf8 = Charset.forName("UTF-8");
|
||||
private final String customerBlinkedManifest = "blinked";
|
||||
|
||||
// unique identifier of the serializer
|
||||
@Override public int identifier() {
|
||||
return 8337;
|
||||
}
|
||||
|
||||
// extract manifest to be stored together with serialized object
|
||||
@Override public String manifest(Object o) {
|
||||
if (o instanceof CustomerBlinked)
|
||||
return customerBlinkedManifest;
|
||||
else
|
||||
return o.getClass().getName();
|
||||
}
|
||||
|
||||
@Override public byte[] toBinary(Object o) {
|
||||
return o.toString().getBytes(utf8); // example serialization
|
||||
}
|
||||
|
||||
@Override public Object fromBinary(byte[] bytes, String manifest) {
|
||||
if (customerBlinkedManifest.equals(manifest))
|
||||
return EventDeserializationSkipped.instance;
|
||||
else
|
||||
return new String(bytes, utf8);
|
||||
}
|
||||
}
|
||||
//#string-serializer-skip-deleved-event-by-manifest
|
||||
|
||||
static
|
||||
//#string-serializer-skip-deleved-event-by-manifest-adapter
|
||||
public class SkippedEventsAwareAdapter implements EventAdapter {
|
||||
@Override public String manifest(Object event) {
|
||||
return "";
|
||||
}
|
||||
|
||||
@Override public Object toJournal(Object event) {
|
||||
return event;
|
||||
}
|
||||
|
||||
@Override public EventSeq fromJournal(Object event, String manifest) {
|
||||
if (event == EventDeserializationSkipped.instance)
|
||||
return EventSeq.empty();
|
||||
else
|
||||
return EventSeq.single(event);
|
||||
}
|
||||
}
|
||||
//#string-serializer-skip-deleved-event-by-manifest-adapter
|
||||
|
||||
|
||||
//#string-serializer-handle-rename
|
||||
static
|
||||
//#string-serializer-handle-rename
|
||||
public class RenamedEventAwareSerializer extends SerializerWithStringManifest {
|
||||
private final Charset utf8 = Charset.forName("UTF-8");
|
||||
|
||||
// unique identifier of the serializer
|
||||
@Override public int identifier() {
|
||||
return 8337;
|
||||
}
|
||||
|
||||
private final String oldPayloadClassName =
|
||||
"docs.persistence.OldPayload"; // class NOT available anymore
|
||||
private final String myPayloadClassName =
|
||||
SamplePayload.class.getName();
|
||||
|
||||
// extract manifest to be stored together with serialized object
|
||||
@Override public String manifest(Object o) {
|
||||
return o.getClass().getName();
|
||||
}
|
||||
|
||||
@Override public byte[] toBinary(Object o) {
|
||||
if (o instanceof SamplePayload) {
|
||||
SamplePayload s = (SamplePayload) o;
|
||||
return s.payload.toString().getBytes(utf8);
|
||||
} else {
|
||||
// previously also handled "old" events here.
|
||||
throw new IllegalArgumentException(
|
||||
"Unable to serialize to bytes, clazz was: " + o.getClass().getName());
|
||||
}
|
||||
}
|
||||
|
||||
@Override public Object fromBinary(byte[] bytes, String manifest) {
|
||||
if (oldPayloadClassName.equals(manifest))
|
||||
return new SamplePayload(new String(bytes, utf8));
|
||||
else if (myPayloadClassName.equals(manifest))
|
||||
return new SamplePayload(new String(bytes, utf8));
|
||||
else throw new IllegalArgumentException("unexpected manifest [" + manifest + "]");
|
||||
}
|
||||
}
|
||||
//#string-serializer-handle-rename
|
||||
|
||||
static
|
||||
//#detach-models
|
||||
// Domain model - highly optimised for domain language and maybe "fluent" usage
|
||||
public class Customer {
|
||||
public final String name;
|
||||
|
||||
public Customer(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
}
|
||||
|
||||
//#detach-models
|
||||
static
|
||||
//#detach-models
|
||||
public class Seat {
|
||||
public final String code;
|
||||
|
||||
public Seat(String code) {
|
||||
this.code = code;
|
||||
}
|
||||
|
||||
public SeatBooked bookFor(Customer customer) {
|
||||
return new SeatBooked(code, customer);
|
||||
}
|
||||
}
|
||||
|
||||
//#detach-models
|
||||
static
|
||||
//#detach-models
|
||||
public class SeatBooked {
|
||||
public final String code;
|
||||
public final Customer customer;
|
||||
|
||||
public SeatBooked(String code, Customer customer) {
|
||||
this.code = code;
|
||||
this.customer = customer;
|
||||
}
|
||||
}
|
||||
|
||||
//#detach-models
|
||||
static
|
||||
//#detach-models
|
||||
// Data model - highly optimised for schema evolution and persistence
|
||||
public class SeatBookedData {
|
||||
public final String code;
|
||||
public final String customerName;
|
||||
|
||||
public SeatBookedData(String code, String customerName) {
|
||||
this.code = code;
|
||||
this.customerName = customerName;
|
||||
}
|
||||
}
|
||||
//#detach-models
|
||||
|
||||
//#detach-models-adapter
|
||||
class DetachedModelsAdapter implements EventAdapter {
|
||||
@Override public String manifest(Object event) {
|
||||
return "";
|
||||
}
|
||||
|
||||
@Override public Object toJournal(Object event) {
|
||||
if (event instanceof SeatBooked) {
|
||||
SeatBooked s = (SeatBooked) event;
|
||||
return new SeatBookedData(s.code, s.customer.name);
|
||||
} else {
|
||||
throw new IllegalArgumentException("Unsupported: " + event.getClass());
|
||||
}
|
||||
}
|
||||
|
||||
@Override public EventSeq fromJournal(Object event, String manifest) {
|
||||
if (event instanceof SeatBookedData) {
|
||||
SeatBookedData d = (SeatBookedData) event;
|
||||
return EventSeq.single(new SeatBooked(d.code, new Customer(d.customerName)));
|
||||
} else {
|
||||
throw new IllegalArgumentException("Unsupported: " + event.getClass());
|
||||
}
|
||||
}
|
||||
}
|
||||
//#detach-models-adapter
|
||||
|
||||
static
|
||||
//#detach-models-adapter-json
|
||||
public class JsonDataModelAdapter implements EventAdapter {
|
||||
|
||||
// use your favorite json library
|
||||
private final ExampleJsonMarshaller marshaller =
|
||||
new ExampleJsonMarshaller();
|
||||
|
||||
@Override public String manifest(Object event) {
|
||||
return "";
|
||||
}
|
||||
|
||||
@Override public JsObject toJournal(Object event) {
|
||||
return marshaller.toJson(event);
|
||||
}
|
||||
|
||||
@Override public EventSeq fromJournal(Object event, String manifest) {
|
||||
if (event instanceof JsObject) {
|
||||
JsObject json = (JsObject) event;
|
||||
return EventSeq.single(marshaller.fromJson(json));
|
||||
} else {
|
||||
throw new IllegalArgumentException(
|
||||
"Unable to fromJournal a non-JSON object! Was: " + event.getClass());
|
||||
}
|
||||
}
|
||||
}
|
||||
//#detach-models-adapter-json
|
||||
|
||||
}
|
||||
|
||||
|
|
@ -0,0 +1,127 @@
|
|||
/**
|
||||
* Copyright (C) 2009-2017 Lightbend Inc. <http://www.lightbend.com>
|
||||
*/
|
||||
|
||||
package jdocs.persistence;
|
||||
|
||||
//#persistent-actor-example
|
||||
|
||||
import akka.actor.ActorRef;
|
||||
import akka.actor.ActorSystem;
|
||||
import akka.actor.Props;
|
||||
import akka.persistence.AbstractPersistentActor;
|
||||
import akka.persistence.SnapshotOffer;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.ArrayList;
|
||||
|
||||
class Cmd implements Serializable {
|
||||
private static final long serialVersionUID = 1L;
|
||||
private final String data;
|
||||
|
||||
public Cmd(String data) {
|
||||
this.data = data;
|
||||
}
|
||||
|
||||
public String getData() {
|
||||
return data;
|
||||
}
|
||||
}
|
||||
|
||||
class Evt implements Serializable {
|
||||
private static final long serialVersionUID = 1L;
|
||||
private final String data;
|
||||
|
||||
public Evt(String data) {
|
||||
this.data = data;
|
||||
}
|
||||
|
||||
public String getData() {
|
||||
return data;
|
||||
}
|
||||
}
|
||||
|
||||
class ExampleState implements Serializable {
|
||||
private static final long serialVersionUID = 1L;
|
||||
private final ArrayList<String> events;
|
||||
|
||||
public ExampleState() {
|
||||
this(new ArrayList<>());
|
||||
}
|
||||
|
||||
public ExampleState(ArrayList<String> events) {
|
||||
this.events = events;
|
||||
}
|
||||
|
||||
public ExampleState copy() {
|
||||
return new ExampleState(new ArrayList<>(events));
|
||||
}
|
||||
|
||||
public void update(Evt evt) {
|
||||
events.add(evt.getData());
|
||||
}
|
||||
|
||||
public int size() {
|
||||
return events.size();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return events.toString();
|
||||
}
|
||||
}
|
||||
|
||||
class ExamplePersistentActor extends AbstractPersistentActor {
|
||||
|
||||
private ExampleState state = new ExampleState();
|
||||
private int snapShotInterval = 1000;
|
||||
|
||||
public int getNumEvents() {
|
||||
return state.size();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String persistenceId() { return "sample-id-1"; }
|
||||
|
||||
@Override
|
||||
public Receive createReceiveRecover() {
|
||||
return receiveBuilder()
|
||||
.match(Evt.class, state::update)
|
||||
.match(SnapshotOffer.class, ss -> state = (ExampleState) ss.snapshot())
|
||||
.build();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Receive createReceive() {
|
||||
return receiveBuilder()
|
||||
.match(Cmd.class, c -> {
|
||||
final String data = c.getData();
|
||||
final Evt evt = new Evt(data + "-" + getNumEvents());
|
||||
persist(evt, (Evt e) -> {
|
||||
state.update(e);
|
||||
getContext().getSystem().eventStream().publish(e);
|
||||
if (lastSequenceNr() % snapShotInterval == 0 && lastSequenceNr() != 0)
|
||||
// IMPORTANT: create a copy of snapshot because ExampleState is mutable
|
||||
saveSnapshot(state.copy());
|
||||
});
|
||||
})
|
||||
.matchEquals("print", s -> System.out.println(state))
|
||||
.build();
|
||||
}
|
||||
}
|
||||
//#persistent-actor-example
|
||||
|
||||
public class PersistentActorExample {
|
||||
public static void main(String... args) throws Exception {
|
||||
final ActorSystem system = ActorSystem.create("example");
|
||||
final ActorRef persistentActor = system.actorOf(Props.create(ExamplePersistentActor.class), "persistentActor-4-java8");
|
||||
persistentActor.tell(new Cmd("foo"), null);
|
||||
persistentActor.tell(new Cmd("baz"), null);
|
||||
persistentActor.tell(new Cmd("bar"), null);
|
||||
persistentActor.tell(new Cmd("buzz"), null);
|
||||
persistentActor.tell("print", null);
|
||||
|
||||
Thread.sleep(10000);
|
||||
system.terminate();
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,94 @@
|
|||
/**
|
||||
* Copyright (C) 2009-2017 Lightbend Inc. <http://www.lightbend.com>
|
||||
*/
|
||||
|
||||
package jdocs.persistence.query;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
import akka.NotUsed;
|
||||
import akka.actor.ActorSystem;
|
||||
import akka.persistence.journal.WriteEventAdapter;
|
||||
import akka.persistence.journal.Tagged;
|
||||
import akka.persistence.query.EventEnvelope;
|
||||
import akka.persistence.query.Sequence;
|
||||
import akka.persistence.query.PersistenceQuery;
|
||||
import akka.persistence.query.journal.leveldb.javadsl.LeveldbReadJournal;
|
||||
import akka.stream.ActorMaterializer;
|
||||
import akka.stream.javadsl.Source;
|
||||
|
||||
public class LeveldbPersistenceQueryDocTest {
|
||||
|
||||
final ActorSystem system = ActorSystem.create();
|
||||
|
||||
public void demonstrateReadJournal() {
|
||||
//#get-read-journal
|
||||
final ActorMaterializer mat = ActorMaterializer.create(system);
|
||||
|
||||
LeveldbReadJournal queries =
|
||||
PersistenceQuery.get(system).getReadJournalFor(LeveldbReadJournal.class,
|
||||
LeveldbReadJournal.Identifier());
|
||||
//#get-read-journal
|
||||
}
|
||||
|
||||
public void demonstrateEventsByPersistenceId() {
|
||||
//#EventsByPersistenceId
|
||||
LeveldbReadJournal queries =
|
||||
PersistenceQuery.get(system).getReadJournalFor(LeveldbReadJournal.class,
|
||||
LeveldbReadJournal.Identifier());
|
||||
|
||||
Source<EventEnvelope, NotUsed> source =
|
||||
queries.eventsByPersistenceId("some-persistence-id", 0, Long.MAX_VALUE);
|
||||
//#EventsByPersistenceId
|
||||
}
|
||||
|
||||
public void demonstrateAllPersistenceIds() {
|
||||
//#AllPersistenceIds
|
||||
LeveldbReadJournal queries =
|
||||
PersistenceQuery.get(system).getReadJournalFor(LeveldbReadJournal.class,
|
||||
LeveldbReadJournal.Identifier());
|
||||
|
||||
Source<String, NotUsed> source = queries.persistenceIds();
|
||||
//#AllPersistenceIds
|
||||
}
|
||||
|
||||
public void demonstrateEventsByTag() {
|
||||
//#EventsByTag
|
||||
LeveldbReadJournal queries =
|
||||
PersistenceQuery.get(system).getReadJournalFor(LeveldbReadJournal.class,
|
||||
LeveldbReadJournal.Identifier());
|
||||
|
||||
Source<EventEnvelope, NotUsed> source =
|
||||
queries.eventsByTag("green", new Sequence(0L));
|
||||
//#EventsByTag
|
||||
}
|
||||
|
||||
static
|
||||
//#tagger
|
||||
public class MyTaggingEventAdapter implements WriteEventAdapter {
|
||||
|
||||
@Override
|
||||
public Object toJournal(Object event) {
|
||||
if (event instanceof String) {
|
||||
String s = (String) event;
|
||||
Set<String> tags = new HashSet<String>();
|
||||
if (s.contains("green")) tags.add("green");
|
||||
if (s.contains("black")) tags.add("black");
|
||||
if (s.contains("blue")) tags.add("blue");
|
||||
if (tags.isEmpty())
|
||||
return event;
|
||||
else
|
||||
return new Tagged(event, tags);
|
||||
} else {
|
||||
return event;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String manifest(Object event) {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
//#tagger
|
||||
}
|
||||
|
|
@ -0,0 +1,126 @@
|
|||
/*
|
||||
* Copyright (C) 2015-2017 Lightbend Inc. <http://www.lightbend.com>
|
||||
*/
|
||||
|
||||
package jdocs.persistence.query;
|
||||
|
||||
import akka.actor.Cancellable;
|
||||
import akka.actor.Scheduler;
|
||||
import akka.japi.Pair;
|
||||
import akka.persistence.PersistentRepr;
|
||||
import akka.persistence.query.Offset;
|
||||
import akka.serialization.Serialization;
|
||||
import akka.serialization.SerializationExtension;
|
||||
import akka.stream.actor.AbstractActorPublisher;
|
||||
|
||||
import akka.actor.Props;
|
||||
import akka.persistence.query.EventEnvelope;
|
||||
import akka.stream.actor.ActorPublisherMessage.Cancel;
|
||||
|
||||
import scala.concurrent.duration.FiniteDuration;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
|
||||
import static java.util.stream.Collectors.toList;
|
||||
|
||||
//#events-by-tag-publisher
|
||||
class MyEventsByTagJavaPublisher extends AbstractActorPublisher<EventEnvelope> {
|
||||
private final Serialization serialization =
|
||||
SerializationExtension.get(getContext().getSystem());
|
||||
|
||||
private final Connection connection;
|
||||
|
||||
private final String tag;
|
||||
|
||||
private final String CONTINUE = "CONTINUE";
|
||||
private final int LIMIT = 1000;
|
||||
private long currentOffset;
|
||||
private List<EventEnvelope> buf = new LinkedList<>();
|
||||
|
||||
private Cancellable continueTask;
|
||||
|
||||
public MyEventsByTagJavaPublisher(Connection connection,
|
||||
String tag,
|
||||
Long offset,
|
||||
FiniteDuration refreshInterval) {
|
||||
this.connection = connection;
|
||||
this.tag = tag;
|
||||
this.currentOffset = offset;
|
||||
|
||||
final Scheduler scheduler = getContext().getSystem().scheduler();
|
||||
this.continueTask = scheduler
|
||||
.schedule(refreshInterval, refreshInterval, getSelf(), CONTINUE,
|
||||
getContext().dispatcher(), getSelf());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Receive createReceive() {
|
||||
return receiveBuilder()
|
||||
.matchEquals(CONTINUE, (in) -> {
|
||||
query();
|
||||
deliverBuf();
|
||||
})
|
||||
.match(Cancel.class, (in) -> {
|
||||
getContext().stop(getSelf());
|
||||
})
|
||||
.build();
|
||||
}
|
||||
|
||||
public static Props props(Connection conn, String tag, Long offset,
|
||||
FiniteDuration refreshInterval) {
|
||||
return Props.create(() ->
|
||||
new MyEventsByTagJavaPublisher(conn, tag, offset, refreshInterval));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void postStop() {
|
||||
continueTask.cancel();
|
||||
}
|
||||
|
||||
private void query() {
|
||||
if (buf.isEmpty()) {
|
||||
final String query = "SELECT id, persistent_repr " +
|
||||
"FROM journal WHERE tag = ? AND id > ? " +
|
||||
"ORDER BY id LIMIT ?";
|
||||
|
||||
try (PreparedStatement s = connection.prepareStatement(query)) {
|
||||
s.setString(1, tag);
|
||||
s.setLong(2, currentOffset);
|
||||
s.setLong(3, LIMIT);
|
||||
try (ResultSet rs = s.executeQuery()) {
|
||||
|
||||
final List<Pair<Long, byte[]>> res = new ArrayList<>(LIMIT);
|
||||
while (rs.next())
|
||||
res.add(Pair.create(rs.getLong(1), rs.getBytes(2)));
|
||||
|
||||
if (!res.isEmpty()) {
|
||||
currentOffset = res.get(res.size() - 1).first();
|
||||
}
|
||||
|
||||
buf = res.stream().map(in -> {
|
||||
final Long id = in.first();
|
||||
final byte[] bytes = in.second();
|
||||
|
||||
final PersistentRepr p =
|
||||
serialization.deserialize(bytes, PersistentRepr.class).get();
|
||||
|
||||
return new EventEnvelope(Offset.sequence(id), p.persistenceId(), p.sequenceNr(), p.payload());
|
||||
}).collect(toList());
|
||||
}
|
||||
} catch(Exception e) {
|
||||
onErrorThenStop(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void deliverBuf() {
|
||||
while (totalDemand() > 0 && !buf.isEmpty())
|
||||
onNext(buf.remove(0));
|
||||
}
|
||||
}
|
||||
//#events-by-tag-publisher
|
||||
Loading…
Add table
Add a link
Reference in a new issue