Formatting java codes with sbt-java-formatter.
This commit is contained in:
parent
27500001ea
commit
998c5a9285
401 changed files with 19750 additions and 17450 deletions
File diff suppressed because it is too large
Load diff
|
|
@ -4,12 +4,12 @@
|
|||
|
||||
package jdocs.persistence;
|
||||
|
||||
//#plugin-imports
|
||||
// #plugin-imports
|
||||
import akka.dispatch.Futures;
|
||||
import akka.persistence.*;
|
||||
import akka.persistence.journal.japi.*;
|
||||
import akka.persistence.snapshot.japi.*;
|
||||
//#plugin-imports
|
||||
// #plugin-imports
|
||||
|
||||
import akka.actor.*;
|
||||
import akka.persistence.journal.leveldb.SharedLeveldbJournal;
|
||||
|
|
@ -28,47 +28,49 @@ 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
|
||||
|
||||
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());
|
||||
}
|
||||
|
||||
//#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
|
||||
};
|
||||
@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) {
|
||||
public Future<Optional<SelectedSnapshot>> doLoadAsync(
|
||||
String persistenceId, SnapshotSelectionCriteria criteria) {
|
||||
return null;
|
||||
}
|
||||
|
||||
|
|
@ -89,7 +91,7 @@ public class LambdaPersistencePluginDocTest {
|
|||
}
|
||||
|
||||
class MyAsyncJournal extends AsyncWriteJournal {
|
||||
//#sync-journal-plugin-api
|
||||
// #sync-journal-plugin-api
|
||||
@Override
|
||||
public Future<Iterable<Optional<Exception>>> doAsyncWriteMessages(
|
||||
Iterable<AtomicWrite> messages) {
|
||||
|
|
@ -102,7 +104,7 @@ public class LambdaPersistencePluginDocTest {
|
|||
return Futures.failed(e);
|
||||
}
|
||||
}
|
||||
//#sync-journal-plugin-api
|
||||
// #sync-journal-plugin-api
|
||||
|
||||
@Override
|
||||
public Future<Void> doAsyncDeleteMessagesTo(String persistenceId, long toSequenceNr) {
|
||||
|
|
@ -110,10 +112,12 @@ public class LambdaPersistencePluginDocTest {
|
|||
}
|
||||
|
||||
@Override
|
||||
public Future<Void> doAsyncReplayMessages(String persistenceId, long fromSequenceNr,
|
||||
long toSequenceNr,
|
||||
long max,
|
||||
Consumer<PersistentRepr> replayCallback) {
|
||||
public Future<Void> doAsyncReplayMessages(
|
||||
String persistenceId,
|
||||
long fromSequenceNr,
|
||||
long toSequenceNr,
|
||||
long max,
|
||||
Consumer<PersistentRepr> replayCallback) {
|
||||
return null;
|
||||
}
|
||||
|
||||
|
|
@ -122,79 +126,83 @@ public class LambdaPersistencePluginDocTest {
|
|||
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\""));
|
||||
}
|
||||
static Object o2 =
|
||||
new Object() {
|
||||
// #journal-tck-java
|
||||
class MyJournalSpecTest extends JavaJournalSpec {
|
||||
|
||||
@Override
|
||||
public CapabilityFlag supportsRejectingNonSerializableObjects() {
|
||||
return CapabilityFlag.off();
|
||||
}
|
||||
}
|
||||
//#journal-tck-java
|
||||
};
|
||||
public MyJournalSpecTest() {
|
||||
super(
|
||||
ConfigFactory.parseString(
|
||||
"persistence.journal.plugin = "
|
||||
+ "\"akka.persistence.journal.leveldb-shared\""));
|
||||
}
|
||||
|
||||
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);
|
||||
@Override
|
||||
public CapabilityFlag supportsRejectingNonSerializableObjects() {
|
||||
return CapabilityFlag.off();
|
||||
}
|
||||
}
|
||||
super.beforeAll();
|
||||
}
|
||||
// #journal-tck-java
|
||||
};
|
||||
|
||||
@Override
|
||||
public void afterAll() {
|
||||
super.afterAll();
|
||||
for (File storageLocation : storageLocations) {
|
||||
FileUtils.deleteRecursively(storageLocation);
|
||||
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\""));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
//#journal-tck-before-after-java
|
||||
};
|
||||
// #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
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -11,7 +11,7 @@ public class PersistenceEventAdapterDocTest {
|
|||
|
||||
@SuppressWarnings("unused")
|
||||
static
|
||||
//#identity-event-adapter
|
||||
// #identity-event-adapter
|
||||
class MyEventAdapter implements EventAdapter {
|
||||
@Override
|
||||
public String manifest(Object event) {
|
||||
|
|
@ -28,5 +28,5 @@ public class PersistenceEventAdapterDocTest {
|
|||
return EventSeq.single(event); // identity
|
||||
}
|
||||
}
|
||||
//#identity-event-adapter
|
||||
// #identity-event-adapter
|
||||
}
|
||||
|
|
|
|||
|
|
@ -12,77 +12,91 @@ import com.typesafe.config.ConfigFactory;
|
|||
|
||||
public class PersistenceMultiDocTest {
|
||||
|
||||
//#default-plugins
|
||||
abstract class AbstractPersistentActorWithDefaultPlugins extends AbstractPersistentActor {
|
||||
@Override
|
||||
public String persistenceId() {
|
||||
return "123";
|
||||
}
|
||||
// #default-plugins
|
||||
abstract class AbstractPersistentActorWithDefaultPlugins extends AbstractPersistentActor {
|
||||
@Override
|
||||
public String persistenceId() {
|
||||
return "123";
|
||||
}
|
||||
//#default-plugins
|
||||
}
|
||||
// #default-plugins
|
||||
|
||||
//#override-plugins
|
||||
abstract class AbstractPersistentActorWithOverridePlugins extends AbstractPersistentActor {
|
||||
@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
|
||||
abstract class AbstractPersistentActorWithOverridePlugins extends AbstractPersistentActor {
|
||||
@Override
|
||||
public String persistenceId() {
|
||||
return "123";
|
||||
}
|
||||
//#override-plugins
|
||||
|
||||
//#runtime-config
|
||||
abstract class AbstractPersistentActorWithRuntimePluginConfig extends AbstractPersistentActor implements RuntimePluginConfig {
|
||||
// Variable that is retrieved at runtime, from an external service for instance.
|
||||
String runtimeDistinction = "foo";
|
||||
|
||||
@Override
|
||||
public String persistenceId() {
|
||||
return "123";
|
||||
}
|
||||
|
||||
// Absolute path to the journal plugin configuration entry in the `reference.conf`
|
||||
@Override
|
||||
public String journalPluginId() {
|
||||
return "journal-plugin-" + runtimeDistinction;
|
||||
}
|
||||
|
||||
// Absolute path to the snapshot store plugin configuration entry in the `reference.conf`
|
||||
@Override
|
||||
public String snapshotPluginId() {
|
||||
return "snapshot-store-plugin-" + runtimeDistinction;
|
||||
}
|
||||
|
||||
// Configuration which contains the journal plugin id defined above
|
||||
@Override
|
||||
public Config journalPluginConfig() {
|
||||
return ConfigFactory.empty().withValue(
|
||||
"journal-plugin-" + runtimeDistinction,
|
||||
getContext().getSystem().settings().config().getValue("journal-plugin") // or a very different configuration coming from an external service.
|
||||
);
|
||||
}
|
||||
|
||||
// Configuration which contains the snapshot store plugin id defined above
|
||||
@Override
|
||||
public Config snapshotPluginConfig() {
|
||||
return ConfigFactory.empty().withValue(
|
||||
"snapshot-plugin-" + runtimeDistinction,
|
||||
getContext().getSystem().settings().config().getValue("snapshot-store-plugin") // or a very different configuration coming from an external service.
|
||||
);
|
||||
}
|
||||
|
||||
// Absolute path to the journal plugin configuration entry in the `reference.conf`
|
||||
@Override
|
||||
public String journalPluginId() {
|
||||
return "akka.persistence.chronicle.journal";
|
||||
}
|
||||
//#runtime-config
|
||||
|
||||
// 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
|
||||
|
||||
// #runtime-config
|
||||
abstract class AbstractPersistentActorWithRuntimePluginConfig extends AbstractPersistentActor
|
||||
implements RuntimePluginConfig {
|
||||
// Variable that is retrieved at runtime, from an external service for instance.
|
||||
String runtimeDistinction = "foo";
|
||||
|
||||
@Override
|
||||
public String persistenceId() {
|
||||
return "123";
|
||||
}
|
||||
|
||||
// Absolute path to the journal plugin configuration entry in the `reference.conf`
|
||||
@Override
|
||||
public String journalPluginId() {
|
||||
return "journal-plugin-" + runtimeDistinction;
|
||||
}
|
||||
|
||||
// Absolute path to the snapshot store plugin configuration entry in the `reference.conf`
|
||||
@Override
|
||||
public String snapshotPluginId() {
|
||||
return "snapshot-store-plugin-" + runtimeDistinction;
|
||||
}
|
||||
|
||||
// Configuration which contains the journal plugin id defined above
|
||||
@Override
|
||||
public Config journalPluginConfig() {
|
||||
return ConfigFactory.empty()
|
||||
.withValue(
|
||||
"journal-plugin-" + runtimeDistinction,
|
||||
getContext()
|
||||
.getSystem()
|
||||
.settings()
|
||||
.config()
|
||||
.getValue(
|
||||
"journal-plugin") // or a very different configuration coming from an external
|
||||
// service.
|
||||
);
|
||||
}
|
||||
|
||||
// Configuration which contains the snapshot store plugin id defined above
|
||||
@Override
|
||||
public Config snapshotPluginConfig() {
|
||||
return ConfigFactory.empty()
|
||||
.withValue(
|
||||
"snapshot-plugin-" + runtimeDistinction,
|
||||
getContext()
|
||||
.getSystem()
|
||||
.settings()
|
||||
.config()
|
||||
.getValue(
|
||||
"snapshot-store-plugin") // or a very different configuration coming from an
|
||||
// external service.
|
||||
);
|
||||
}
|
||||
}
|
||||
// #runtime-config
|
||||
|
||||
}
|
||||
|
|
|
|||
|
|
@ -35,10 +35,10 @@ 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
|
||||
// #advanced-journal-query-types
|
||||
static class RichEvent {
|
||||
public final Set<String> tags;
|
||||
public final Object payload;
|
||||
|
||||
public RichEvent(Set<String> tags, Object payload) {
|
||||
|
|
@ -46,12 +46,12 @@ public class PersistenceQueryDocTest {
|
|||
this.payload = payload;
|
||||
}
|
||||
}
|
||||
//#advanced-journal-query-types
|
||||
// #advanced-journal-query-types
|
||||
|
||||
static
|
||||
//#advanced-journal-query-types
|
||||
public
|
||||
// #advanced-journal-query-types
|
||||
// a plugin can provide:
|
||||
public final class QueryMetadata{
|
||||
static final class QueryMetadata {
|
||||
public final boolean deterministicOrder;
|
||||
public final boolean infinite;
|
||||
|
||||
|
|
@ -60,11 +60,11 @@ public class PersistenceQueryDocTest {
|
|||
this.infinite = infinite;
|
||||
}
|
||||
}
|
||||
//#advanced-journal-query-types
|
||||
// #advanced-journal-query-types
|
||||
|
||||
static
|
||||
//#my-read-journal
|
||||
public class MyReadJournalProvider implements ReadJournalProvider {
|
||||
public
|
||||
// #my-read-journal
|
||||
static class MyReadJournalProvider implements ReadJournalProvider {
|
||||
private final MyJavadslReadJournal javadslReadJournal;
|
||||
|
||||
public MyReadJournalProvider(ExtendedActorSystem system, Config config) {
|
||||
|
|
@ -81,52 +81,54 @@ public class PersistenceQueryDocTest {
|
|||
return this.javadslReadJournal;
|
||||
}
|
||||
}
|
||||
//#my-read-journal
|
||||
// #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 {
|
||||
public
|
||||
// #my-read-journal
|
||||
static 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);
|
||||
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.
|
||||
* 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.
|
||||
* <p>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){
|
||||
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());
|
||||
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
|
||||
return eventsByTag(tag, Offset.sequence(0L)); // recursive
|
||||
else
|
||||
throw new IllegalArgumentException("MyJavadslReadJournal does not support " + offset.getClass().getName() + " offsets");
|
||||
throw new IllegalArgumentException(
|
||||
"MyJavadslReadJournal does not support " + offset.getClass().getName() + " offsets");
|
||||
}
|
||||
|
||||
@Override
|
||||
public Source<EventEnvelope, NotUsed> eventsByPersistenceId(String persistenceId,
|
||||
long fromSequenceNr, long toSequenceNr) {
|
||||
public Source<EventEnvelope, NotUsed> eventsByPersistenceId(
|
||||
String persistenceId, long fromSequenceNr, long toSequenceNr) {
|
||||
// implement in a similar way as eventsByTag
|
||||
throw new UnsupportedOperationException("Not implemented yet");
|
||||
}
|
||||
|
|
@ -145,24 +147,23 @@ public class PersistenceQueryDocTest {
|
|||
|
||||
// possibility to add more plugin specific queries
|
||||
|
||||
//#advanced-journal-query-definition
|
||||
// #advanced-journal-query-definition
|
||||
public Source<RichEvent, QueryMetadata> byTagsWithMeta(Set<String> tags) {
|
||||
//#advanced-journal-query-definition
|
||||
// #advanced-journal-query-definition
|
||||
// implement in a similar way as eventsByTag
|
||||
throw new UnsupportedOperationException("Not implemented yet");
|
||||
}
|
||||
|
||||
}
|
||||
//#my-read-journal
|
||||
// #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 {
|
||||
public
|
||||
// #my-read-journal
|
||||
static 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;
|
||||
|
||||
|
|
@ -179,8 +180,9 @@ public class PersistenceQueryDocTest {
|
|||
@Override
|
||||
public akka.stream.scaladsl.Source<EventEnvelope, NotUsed> eventsByPersistenceId(
|
||||
String persistenceId, long fromSequenceNr, long toSequenceNr) {
|
||||
return javadslReadJournal.eventsByPersistenceId(persistenceId, fromSequenceNr,
|
||||
toSequenceNr).asScala();
|
||||
return javadslReadJournal
|
||||
.eventsByPersistenceId(persistenceId, fromSequenceNr, toSequenceNr)
|
||||
.asScala();
|
||||
}
|
||||
|
||||
@Override
|
||||
|
|
@ -200,61 +202,64 @@ public class PersistenceQueryDocTest {
|
|||
Set<String> jTags = scala.collection.JavaConverters.setAsJavaSetConverter(tags).asJava();
|
||||
return javadslReadJournal.byTagsWithMeta(jTags).asScala();
|
||||
}
|
||||
|
||||
}
|
||||
//#my-read-journal
|
||||
// #my-read-journal
|
||||
|
||||
void demonstrateBasicUsage() {
|
||||
final ActorSystem system = ActorSystem.create();
|
||||
|
||||
//#basic-usage
|
||||
// #basic-usage
|
||||
// obtain read journal by plugin id
|
||||
final MyJavadslReadJournal readJournal =
|
||||
PersistenceQuery.get(system).getReadJournalFor(MyJavadslReadJournal.class,
|
||||
"akka.persistence.query.my-read-journal");
|
||||
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);
|
||||
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
|
||||
// #basic-usage
|
||||
}
|
||||
|
||||
void demonstrateAllPersistenceIdsLive() {
|
||||
final MyJavadslReadJournal readJournal =
|
||||
PersistenceQuery.get(system).getReadJournalFor(MyJavadslReadJournal.class,
|
||||
"akka.persistence.query.my-read-journal");
|
||||
PersistenceQuery.get(system)
|
||||
.getReadJournalFor(
|
||||
MyJavadslReadJournal.class, "akka.persistence.query.my-read-journal");
|
||||
|
||||
//#all-persistence-ids-live
|
||||
// #all-persistence-ids-live
|
||||
readJournal.persistenceIds();
|
||||
//#all-persistence-ids-live
|
||||
// #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");
|
||||
PersistenceQuery.get(system)
|
||||
.getReadJournalFor(
|
||||
MyJavadslReadJournal.class, "akka.persistence.query.my-read-journal");
|
||||
|
||||
//#all-persistence-ids-snap
|
||||
// #all-persistence-ids-snap
|
||||
readJournal.currentPersistenceIds();
|
||||
//#all-persistence-ids-snap
|
||||
// #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");
|
||||
PersistenceQuery.get(system)
|
||||
.getReadJournalFor(
|
||||
MyJavadslReadJournal.class, "akka.persistence.query.my-read-journal");
|
||||
|
||||
//#events-by-persistent-id
|
||||
// #events-by-persistent-id
|
||||
readJournal.eventsByPersistenceId("user-us-1337", 0L, Long.MAX_VALUE);
|
||||
//#events-by-persistent-id
|
||||
// #events-by-persistent-id
|
||||
}
|
||||
|
||||
void demonstrateEventsByTag() {
|
||||
|
|
@ -262,58 +267,71 @@ public class PersistenceQueryDocTest {
|
|||
final ActorMaterializer mat = ActorMaterializer.create(system);
|
||||
|
||||
final MyJavadslReadJournal readJournal =
|
||||
PersistenceQuery.get(system).getReadJournalFor(MyJavadslReadJournal.class,
|
||||
"akka.persistence.query.my-read-journal");
|
||||
PersistenceQuery.get(system)
|
||||
.getReadJournalFor(
|
||||
MyJavadslReadJournal.class, "akka.persistence.query.my-read-journal");
|
||||
|
||||
//#events-by-tag
|
||||
// #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));
|
||||
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);
|
||||
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
|
||||
// #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");
|
||||
PersistenceQuery.get(system)
|
||||
.getReadJournalFor(
|
||||
MyJavadslReadJournal.class, "akka.persistence.query.my-read-journal");
|
||||
|
||||
//#advanced-journal-query-usage
|
||||
// #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;
|
||||
});
|
||||
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);
|
||||
events
|
||||
.map(
|
||||
event -> {
|
||||
System.out.println("Event payload: " + event.payload);
|
||||
return event.payload;
|
||||
})
|
||||
.runWith(Sink.ignore(), mat);
|
||||
|
||||
|
||||
//#advanced-journal-query-usage
|
||||
// #advanced-journal-query-usage
|
||||
}
|
||||
|
||||
class ReactiveStreamsCompatibleDBDriver {
|
||||
|
|
@ -327,54 +345,54 @@ public class PersistenceQueryDocTest {
|
|||
final ActorMaterializer mat = ActorMaterializer.create(system);
|
||||
|
||||
final MyJavadslReadJournal readJournal =
|
||||
PersistenceQuery.get(system).getReadJournalFor(MyJavadslReadJournal.class,
|
||||
"akka.persistence.query.my-read-journal");
|
||||
PersistenceQuery.get(system)
|
||||
.getReadJournalFor(
|
||||
MyJavadslReadJournal.class, "akka.persistence.query.my-read-journal");
|
||||
|
||||
|
||||
//#projection-into-different-store-rs
|
||||
// #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
|
||||
.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
|
||||
// #projection-into-different-store-simple-classes
|
||||
class ExampleStore {
|
||||
CompletionStage<Void> save(Object any) {
|
||||
// ...
|
||||
//#projection-into-different-store-simple-classes
|
||||
// #projection-into-different-store-simple-classes
|
||||
return null;
|
||||
//#projection-into-different-store-simple-classes
|
||||
// #projection-into-different-store-simple-classes
|
||||
}
|
||||
}
|
||||
//#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");
|
||||
PersistenceQuery.get(system)
|
||||
.getReadJournalFor(
|
||||
MyJavadslReadJournal.class, "akka.persistence.query.my-read-journal");
|
||||
|
||||
|
||||
//#projection-into-different-store-simple
|
||||
// #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
|
||||
.eventsByTag("bid", new Sequence(0L))
|
||||
.mapAsync(1, store::save)
|
||||
.runWith(Sink.ignore(), mat);
|
||||
// #projection-into-different-store-simple
|
||||
}
|
||||
|
||||
//#projection-into-different-store
|
||||
// #projection-into-different-store
|
||||
class MyResumableProjection {
|
||||
private final String name;
|
||||
|
||||
|
|
@ -384,30 +402,30 @@ public class PersistenceQueryDocTest {
|
|||
|
||||
public CompletionStage<Long> saveProgress(Offset offset) {
|
||||
// ...
|
||||
//#projection-into-different-store
|
||||
// #projection-into-different-store
|
||||
return null;
|
||||
//#projection-into-different-store
|
||||
// #projection-into-different-store
|
||||
}
|
||||
|
||||
public CompletionStage<Long> latestOffset() {
|
||||
// ...
|
||||
//#projection-into-different-store
|
||||
// #projection-into-different-store
|
||||
return null;
|
||||
//#projection-into-different-store
|
||||
// #projection-into-different-store
|
||||
}
|
||||
}
|
||||
//#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");
|
||||
PersistenceQuery.get(system)
|
||||
.getReadJournalFor(
|
||||
MyJavadslReadJournal.class, "akka.persistence.query.my-read-journal");
|
||||
|
||||
|
||||
//#projection-into-different-store-actor-run
|
||||
// #projection-into-different-store-actor-run
|
||||
final Duration timeout = Duration.ofSeconds(3);
|
||||
|
||||
final MyResumableProjection bidProjection = new MyResumableProjection("bid");
|
||||
|
|
@ -415,19 +433,22 @@ public class PersistenceQueryDocTest {
|
|||
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);
|
||||
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);
|
||||
.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
|
||||
// #projection-into-different-store-actor-run
|
||||
|
||||
class ComplexState {
|
||||
|
||||
|
|
@ -442,7 +463,7 @@ public class PersistenceQueryDocTest {
|
|||
}
|
||||
}
|
||||
|
||||
//#projection-into-different-store-actor
|
||||
// #projection-into-different-store-actor
|
||||
final class TheOneWhoWritesToQueryJournal extends AbstractActor {
|
||||
private final ExampleStore store;
|
||||
|
||||
|
|
@ -455,23 +476,21 @@ public class PersistenceQueryDocTest {
|
|||
@Override
|
||||
public Receive createReceive() {
|
||||
return receiveBuilder()
|
||||
.matchAny(message -> {
|
||||
state = updateState(state, message);
|
||||
.matchAny(
|
||||
message -> {
|
||||
state = updateState(state, message);
|
||||
|
||||
// example saving logic that requires state to become ready:
|
||||
if (state.readyToSave())
|
||||
store.save(Record.of(state));
|
||||
|
||||
})
|
||||
.build();
|
||||
// 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
|
||||
// #projection-into-different-store-actor
|
||||
|
||||
}
|
||||
|
|
|
|||
|
|
@ -18,84 +18,88 @@ import akka.serialization.SerializerWithStringManifest;
|
|||
|
||||
public class PersistenceSchemaEvolutionDocTest {
|
||||
|
||||
static
|
||||
//#protobuf-read-optional-model
|
||||
public enum SeatType {
|
||||
Window("W"), Aisle("A"), Other("O"), Unknown("");
|
||||
|
||||
public
|
||||
// #protobuf-read-optional-model
|
||||
static 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;
|
||||
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 {
|
||||
// #protobuf-read-optional-model
|
||||
|
||||
public
|
||||
// #protobuf-read-optional-model
|
||||
static 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
|
||||
// #protobuf-read-optional-model
|
||||
|
||||
public
|
||||
// #protobuf-read-optional
|
||||
/**
|
||||
* Example serializer impl which uses protocol buffers generated classes (proto.*)
|
||||
* to perform the to/from binary marshalling.
|
||||
* 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() {
|
||||
static class AddedFieldsSerializerWithProtobuf extends SerializerWithStringManifest {
|
||||
@Override
|
||||
public int identifier() {
|
||||
return 67876;
|
||||
}
|
||||
|
||||
private final String seatReservedManifest = SeatReserved.class.getName();
|
||||
|
||||
@Override public String manifest(Object o){
|
||||
@Override
|
||||
public String manifest(Object o) {
|
||||
return o.getClass().getName();
|
||||
}
|
||||
|
||||
@Override public Object fromBinary(byte[] bytes, String manifest) throws NotSerializableException{
|
||||
@Override
|
||||
public Object fromBinary(byte[] bytes, String manifest) throws NotSerializableException {
|
||||
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 NotSerializableException("Unable to handle manifest: " + manifest);
|
||||
throw new NotSerializableException("Unable to handle manifest: " + manifest);
|
||||
}
|
||||
}
|
||||
|
||||
@Override public byte[] toBinary(Object o) {
|
||||
@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();
|
||||
|
||||
.setRow(s.row)
|
||||
.setLetter(s.letter)
|
||||
.setSeatType(s.seatType.code)
|
||||
.build()
|
||||
.toByteArray();
|
||||
|
||||
} else {
|
||||
throw new IllegalArgumentException("Unable to handle: " + o);
|
||||
}
|
||||
|
|
@ -109,20 +113,16 @@ public class PersistenceSchemaEvolutionDocTest {
|
|||
|
||||
// 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;
|
||||
if (p.hasSeatType()) return SeatType.fromCode(p.getSeatType());
|
||||
else return SeatType.Unknown;
|
||||
}
|
||||
|
||||
}
|
||||
//#protobuf-read-optional
|
||||
|
||||
|
||||
// #protobuf-read-optional
|
||||
|
||||
public static class RenamePlainJson {
|
||||
static
|
||||
//#rename-plain-json
|
||||
public class JsonRenamedFieldAdapter implements EventAdapter {
|
||||
public
|
||||
// #rename-plain-json
|
||||
static class JsonRenamedFieldAdapter implements EventAdapter {
|
||||
// use your favorite json library
|
||||
private final ExampleJsonMarshaller marshaller = new ExampleJsonMarshaller();
|
||||
|
||||
|
|
@ -130,103 +130,109 @@ public class PersistenceSchemaEvolutionDocTest {
|
|||
private final String V2 = "v2";
|
||||
|
||||
// this could be done independently for each event type
|
||||
@Override public String manifest(Object event) {
|
||||
@Override
|
||||
public String manifest(Object event) {
|
||||
return V2;
|
||||
}
|
||||
|
||||
@Override public JsObject toJournal(Object event) {
|
||||
@Override
|
||||
public JsObject toJournal(Object event) {
|
||||
return marshaller.toJson(event);
|
||||
}
|
||||
|
||||
@Override public EventSeq fromJournal(Object event, String manifest) {
|
||||
@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");
|
||||
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());
|
||||
} 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;
|
||||
JsObject renamed = json;
|
||||
return renamed;
|
||||
}
|
||||
|
||||
}
|
||||
//#rename-plain-json
|
||||
// #rename-plain-json
|
||||
}
|
||||
|
||||
|
||||
public static class SimplestCustomSerializer {
|
||||
|
||||
static
|
||||
//#simplest-custom-serializer-model
|
||||
public class Person {
|
||||
public
|
||||
// #simplest-custom-serializer-model
|
||||
static 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
|
||||
// #simplest-custom-serializer-model
|
||||
|
||||
static
|
||||
//#simplest-custom-serializer
|
||||
public
|
||||
// #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.
|
||||
* <p>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 {
|
||||
static 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() {
|
||||
@Override
|
||||
public int identifier() {
|
||||
return 1234567;
|
||||
}
|
||||
|
||||
// extract manifest to be stored together with serialized object
|
||||
@Override public String manifest(Object o) {
|
||||
@Override
|
||||
public String manifest(Object o) {
|
||||
return o.getClass().getName();
|
||||
}
|
||||
|
||||
// serialize the object
|
||||
@Override public byte[] toBinary(Object obj) {
|
||||
@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());
|
||||
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) throws NotSerializableException {
|
||||
@Override
|
||||
public Object fromBinary(byte[] bytes, String manifest) throws NotSerializableException {
|
||||
if (personManifest.equals(manifest)) {
|
||||
String nameAndSurname = new String(bytes, utf8);
|
||||
String[] parts = nameAndSurname.split("[|]");
|
||||
return new Person(parts[0], parts[1]);
|
||||
} else {
|
||||
throw new NotSerializableException(
|
||||
"Unable to deserialize from bytes, manifest was: " + manifest +
|
||||
"! Bytes length: " + bytes.length);
|
||||
"Unable to deserialize from bytes, manifest was: "
|
||||
+ manifest
|
||||
+ "! Bytes length: "
|
||||
+ bytes.length);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
//#simplest-custom-serializer
|
||||
// #simplest-custom-serializer
|
||||
}
|
||||
|
||||
|
||||
|
||||
public static class SamplePayload {
|
||||
private final Object payload;
|
||||
|
||||
|
|
@ -239,78 +245,77 @@ public class PersistenceSchemaEvolutionDocTest {
|
|||
}
|
||||
}
|
||||
|
||||
//#split-events-during-recovery
|
||||
// #split-events-during-recovery
|
||||
interface V1 {};
|
||||
|
||||
interface V2 {}
|
||||
|
||||
//#split-events-during-recovery
|
||||
static
|
||||
//#split-events-during-recovery
|
||||
|
||||
// #split-events-during-recovery
|
||||
public
|
||||
// #split-events-during-recovery
|
||||
// V1 event:
|
||||
public class UserDetailsChanged implements V1 {
|
||||
static 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
|
||||
|
||||
// #split-events-during-recovery
|
||||
public
|
||||
// #split-events-during-recovery
|
||||
// corresponding V2 events:
|
||||
public class UserNameChanged implements V2 {
|
||||
static 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 {
|
||||
// #split-events-during-recovery
|
||||
public
|
||||
// #split-events-during-recovery
|
||||
static class UserAddressChanged implements V2 {
|
||||
public final String address;
|
||||
|
||||
public UserAddressChanged(String address) {
|
||||
this.address = address;
|
||||
}
|
||||
}
|
||||
|
||||
//#split-events-during-recovery
|
||||
static
|
||||
//#split-events-during-recovery
|
||||
|
||||
// #split-events-during-recovery
|
||||
public
|
||||
// #split-events-during-recovery
|
||||
// event splitting adapter:
|
||||
public class UserEventsAdapter implements EventAdapter {
|
||||
@Override public String manifest(Object event) {
|
||||
static class UserEventsAdapter implements EventAdapter {
|
||||
@Override
|
||||
public String manifest(Object event) {
|
||||
return "";
|
||||
}
|
||||
|
||||
@Override public EventSeq fromJournal(Object event, String manifest) {
|
||||
|
||||
@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));
|
||||
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) {
|
||||
|
||||
@Override
|
||||
public Object toJournal(Object event) {
|
||||
return event;
|
||||
}
|
||||
}
|
||||
//#split-events-during-recovery
|
||||
|
||||
|
||||
static public class CustomerBlinked {
|
||||
// #split-events-during-recovery
|
||||
|
||||
public static class CustomerBlinked {
|
||||
public final long customerId;
|
||||
|
||||
public CustomerBlinked(long customerId) {
|
||||
|
|
@ -318,92 +323,92 @@ public class PersistenceSchemaEvolutionDocTest {
|
|||
}
|
||||
}
|
||||
|
||||
static
|
||||
//#string-serializer-skip-deleved-event-by-manifest
|
||||
public class EventDeserializationSkipped {
|
||||
public static EventDeserializationSkipped instance =
|
||||
new EventDeserializationSkipped();
|
||||
|
||||
private EventDeserializationSkipped() {
|
||||
}
|
||||
public
|
||||
// #string-serializer-skip-deleved-event-by-manifest
|
||||
static 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 {
|
||||
// #string-serializer-skip-deleved-event-by-manifest
|
||||
public
|
||||
// #string-serializer-skip-deleved-event-by-manifest
|
||||
static 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() {
|
||||
@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 String manifest(Object o) {
|
||||
if (o instanceof CustomerBlinked) return customerBlinkedManifest;
|
||||
else return o.getClass().getName();
|
||||
}
|
||||
|
||||
@Override public byte[] toBinary(Object o) {
|
||||
|
||||
@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);
|
||||
|
||||
@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
|
||||
// #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) {
|
||||
public
|
||||
// #string-serializer-skip-deleved-event-by-manifest-adapter
|
||||
static class SkippedEventsAwareAdapter implements EventAdapter {
|
||||
@Override
|
||||
public String manifest(Object event) {
|
||||
return "";
|
||||
}
|
||||
|
||||
@Override public Object toJournal(Object event) {
|
||||
|
||||
@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);
|
||||
|
||||
@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 {
|
||||
// #string-serializer-skip-deleved-event-by-manifest-adapter
|
||||
|
||||
// #string-serializer-handle-rename
|
||||
public
|
||||
// #string-serializer-handle-rename
|
||||
static class RenamedEventAwareSerializer extends SerializerWithStringManifest {
|
||||
private final Charset utf8 = Charset.forName("UTF-8");
|
||||
|
||||
// unique identifier of the serializer
|
||||
@Override public int identifier() {
|
||||
@Override
|
||||
public int identifier() {
|
||||
return 8337;
|
||||
}
|
||||
|
||||
private final String oldPayloadClassName =
|
||||
private final String oldPayloadClassName =
|
||||
"docs.persistence.OldPayload"; // class NOT available anymore
|
||||
private final String myPayloadClassName =
|
||||
SamplePayload.class.getName();
|
||||
|
||||
private final String myPayloadClassName = SamplePayload.class.getName();
|
||||
|
||||
// extract manifest to be stored together with serialized object
|
||||
@Override public String manifest(Object o) {
|
||||
@Override
|
||||
public String manifest(Object o) {
|
||||
return o.getClass().getName();
|
||||
}
|
||||
|
||||
@Override public byte[] toBinary(Object o) {
|
||||
|
||||
@Override
|
||||
public byte[] toBinary(Object o) {
|
||||
if (o instanceof SamplePayload) {
|
||||
SamplePayload s = (SamplePayload) o;
|
||||
return s.payload.toString().getBytes(utf8);
|
||||
|
|
@ -413,78 +418,80 @@ public class PersistenceSchemaEvolutionDocTest {
|
|||
"Unable to serialize to bytes, clazz was: " + o.getClass().getName());
|
||||
}
|
||||
}
|
||||
|
||||
@Override public Object fromBinary(byte[] bytes, String manifest) throws NotSerializableException {
|
||||
if (oldPayloadClassName.equals(manifest))
|
||||
return new SamplePayload(new String(bytes, utf8));
|
||||
|
||||
@Override
|
||||
public Object fromBinary(byte[] bytes, String manifest) throws NotSerializableException {
|
||||
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 NotSerializableException("unexpected manifest [" + manifest + "]");
|
||||
}
|
||||
}
|
||||
//#string-serializer-handle-rename
|
||||
|
||||
static
|
||||
//#detach-models
|
||||
// #string-serializer-handle-rename
|
||||
|
||||
public
|
||||
// #detach-models
|
||||
// Domain model - highly optimised for domain language and maybe "fluent" usage
|
||||
public class Customer {
|
||||
static class Customer {
|
||||
public final String name;
|
||||
|
||||
public Customer(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
}
|
||||
|
||||
//#detach-models
|
||||
static
|
||||
//#detach-models
|
||||
public class Seat {
|
||||
|
||||
// #detach-models
|
||||
public
|
||||
// #detach-models
|
||||
static 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 {
|
||||
|
||||
// #detach-models
|
||||
public
|
||||
// #detach-models
|
||||
static 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
|
||||
|
||||
// #detach-models
|
||||
public
|
||||
// #detach-models
|
||||
// Data model - highly optimised for schema evolution and persistence
|
||||
public class SeatBookedData {
|
||||
static 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
|
||||
// #detach-models
|
||||
|
||||
// #detach-models-adapter
|
||||
class DetachedModelsAdapter implements EventAdapter {
|
||||
@Override public String manifest(Object event) {
|
||||
@Override
|
||||
public String manifest(Object event) {
|
||||
return "";
|
||||
}
|
||||
|
||||
@Override public Object toJournal(Object event) {
|
||||
|
||||
@Override
|
||||
public Object toJournal(Object event) {
|
||||
if (event instanceof SeatBooked) {
|
||||
SeatBooked s = (SeatBooked) event;
|
||||
return new SeatBookedData(s.code, s.customer.name);
|
||||
|
|
@ -492,8 +499,9 @@ public class PersistenceSchemaEvolutionDocTest {
|
|||
throw new IllegalArgumentException("Unsupported: " + event.getClass());
|
||||
}
|
||||
}
|
||||
|
||||
@Override public EventSeq fromJournal(Object event, String manifest) {
|
||||
|
||||
@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)));
|
||||
|
|
@ -502,35 +510,36 @@ public class PersistenceSchemaEvolutionDocTest {
|
|||
}
|
||||
}
|
||||
}
|
||||
//#detach-models-adapter
|
||||
|
||||
static
|
||||
//#detach-models-adapter-json
|
||||
public class JsonDataModelAdapter implements EventAdapter {
|
||||
// #detach-models-adapter
|
||||
|
||||
public
|
||||
// #detach-models-adapter-json
|
||||
static class JsonDataModelAdapter implements EventAdapter {
|
||||
|
||||
// use your favorite json library
|
||||
private final ExampleJsonMarshaller marshaller =
|
||||
new ExampleJsonMarshaller();
|
||||
|
||||
@Override public String manifest(Object event) {
|
||||
private final ExampleJsonMarshaller marshaller = new ExampleJsonMarshaller();
|
||||
|
||||
@Override
|
||||
public String manifest(Object event) {
|
||||
return "";
|
||||
}
|
||||
|
||||
@Override public JsObject toJournal(Object event) {
|
||||
|
||||
@Override
|
||||
public JsObject toJournal(Object event) {
|
||||
return marshaller.toJson(event);
|
||||
}
|
||||
|
||||
@Override public EventSeq fromJournal(Object event, String manifest) {
|
||||
@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());
|
||||
"Unable to fromJournal a non-JSON object! Was: " + event.getClass());
|
||||
}
|
||||
}
|
||||
}
|
||||
//#detach-models-adapter-json
|
||||
// #detach-models-adapter-json
|
||||
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@
|
|||
|
||||
package jdocs.persistence;
|
||||
|
||||
//#persistent-actor-example
|
||||
// #persistent-actor-example
|
||||
|
||||
import akka.actor.ActorRef;
|
||||
import akka.actor.ActorSystem;
|
||||
|
|
@ -16,112 +16,119 @@ import java.io.Serializable;
|
|||
import java.util.ArrayList;
|
||||
|
||||
class Cmd implements Serializable {
|
||||
private static final long serialVersionUID = 1L;
|
||||
private final String data;
|
||||
private static final long serialVersionUID = 1L;
|
||||
private final String data;
|
||||
|
||||
public Cmd(String data) {
|
||||
this.data = data;
|
||||
}
|
||||
public Cmd(String data) {
|
||||
this.data = data;
|
||||
}
|
||||
|
||||
public String getData() {
|
||||
return data;
|
||||
}
|
||||
public String getData() {
|
||||
return data;
|
||||
}
|
||||
}
|
||||
|
||||
class Evt implements Serializable {
|
||||
private static final long serialVersionUID = 1L;
|
||||
private final String data;
|
||||
private static final long serialVersionUID = 1L;
|
||||
private final String data;
|
||||
|
||||
public Evt(String data) {
|
||||
this.data = data;
|
||||
}
|
||||
public Evt(String data) {
|
||||
this.data = data;
|
||||
}
|
||||
|
||||
public String getData() {
|
||||
return data;
|
||||
}
|
||||
public String getData() {
|
||||
return data;
|
||||
}
|
||||
}
|
||||
|
||||
class ExampleState implements Serializable {
|
||||
private static final long serialVersionUID = 1L;
|
||||
private final ArrayList<String> events;
|
||||
private static final long serialVersionUID = 1L;
|
||||
private final ArrayList<String> events;
|
||||
|
||||
public ExampleState() {
|
||||
this(new ArrayList<>());
|
||||
}
|
||||
public ExampleState() {
|
||||
this(new ArrayList<>());
|
||||
}
|
||||
|
||||
public ExampleState(ArrayList<String> events) {
|
||||
this.events = events;
|
||||
}
|
||||
public ExampleState(ArrayList<String> events) {
|
||||
this.events = events;
|
||||
}
|
||||
|
||||
public ExampleState copy() {
|
||||
return new ExampleState(new ArrayList<>(events));
|
||||
}
|
||||
public ExampleState copy() {
|
||||
return new ExampleState(new ArrayList<>(events));
|
||||
}
|
||||
|
||||
public void update(Evt evt) {
|
||||
events.add(evt.getData());
|
||||
}
|
||||
public void update(Evt evt) {
|
||||
events.add(evt.getData());
|
||||
}
|
||||
|
||||
public int size() {
|
||||
return events.size();
|
||||
}
|
||||
public int size() {
|
||||
return events.size();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return events.toString();
|
||||
}
|
||||
@Override
|
||||
public String toString() {
|
||||
return events.toString();
|
||||
}
|
||||
}
|
||||
|
||||
class ExamplePersistentActor extends AbstractPersistentActor {
|
||||
|
||||
private ExampleState state = new ExampleState();
|
||||
private int snapShotInterval = 1000;
|
||||
private ExampleState state = new ExampleState();
|
||||
private int snapShotInterval = 1000;
|
||||
|
||||
public int getNumEvents() {
|
||||
return state.size();
|
||||
}
|
||||
public int getNumEvents() {
|
||||
return state.size();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String persistenceId() { return "sample-id-1"; }
|
||||
@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 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 -> {
|
||||
@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().getEventStream().publish(e);
|
||||
if (lastSequenceNr() % snapShotInterval == 0 && lastSequenceNr() != 0)
|
||||
persist(
|
||||
evt,
|
||||
(Evt e) -> {
|
||||
state.update(e);
|
||||
getContext().getSystem().getEventStream().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();
|
||||
}
|
||||
.matchEquals("print", s -> System.out.println(state))
|
||||
.build();
|
||||
}
|
||||
}
|
||||
//#persistent-actor-example
|
||||
// #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);
|
||||
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();
|
||||
}
|
||||
Thread.sleep(10000);
|
||||
system.terminate();
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -23,50 +23,49 @@ public class LeveldbPersistenceQueryDocTest {
|
|||
final ActorSystem system = ActorSystem.create();
|
||||
|
||||
public void demonstrateReadJournal() {
|
||||
//#get-read-journal
|
||||
// #get-read-journal
|
||||
final ActorMaterializer mat = ActorMaterializer.create(system);
|
||||
|
||||
|
||||
LeveldbReadJournal queries =
|
||||
PersistenceQuery.get(system).getReadJournalFor(LeveldbReadJournal.class,
|
||||
LeveldbReadJournal.Identifier());
|
||||
//#get-read-journal
|
||||
PersistenceQuery.get(system)
|
||||
.getReadJournalFor(LeveldbReadJournal.class, LeveldbReadJournal.Identifier());
|
||||
// #get-read-journal
|
||||
}
|
||||
|
||||
|
||||
public void demonstrateEventsByPersistenceId() {
|
||||
//#EventsByPersistenceId
|
||||
// #EventsByPersistenceId
|
||||
LeveldbReadJournal queries =
|
||||
PersistenceQuery.get(system).getReadJournalFor(LeveldbReadJournal.class,
|
||||
LeveldbReadJournal.Identifier());
|
||||
|
||||
PersistenceQuery.get(system)
|
||||
.getReadJournalFor(LeveldbReadJournal.class, LeveldbReadJournal.Identifier());
|
||||
|
||||
Source<EventEnvelope, NotUsed> source =
|
||||
queries.eventsByPersistenceId("some-persistence-id", 0, Long.MAX_VALUE);
|
||||
//#EventsByPersistenceId
|
||||
// #EventsByPersistenceId
|
||||
}
|
||||
|
||||
|
||||
public void demonstrateAllPersistenceIds() {
|
||||
//#AllPersistenceIds
|
||||
// #AllPersistenceIds
|
||||
LeveldbReadJournal queries =
|
||||
PersistenceQuery.get(system).getReadJournalFor(LeveldbReadJournal.class,
|
||||
LeveldbReadJournal.Identifier());
|
||||
|
||||
PersistenceQuery.get(system)
|
||||
.getReadJournalFor(LeveldbReadJournal.class, LeveldbReadJournal.Identifier());
|
||||
|
||||
Source<String, NotUsed> source = queries.persistenceIds();
|
||||
//#AllPersistenceIds
|
||||
// #AllPersistenceIds
|
||||
}
|
||||
|
||||
|
||||
public void demonstrateEventsByTag() {
|
||||
//#EventsByTag
|
||||
// #EventsByTag
|
||||
LeveldbReadJournal queries =
|
||||
PersistenceQuery.get(system).getReadJournalFor(LeveldbReadJournal.class,
|
||||
LeveldbReadJournal.Identifier());
|
||||
|
||||
Source<EventEnvelope, NotUsed> source =
|
||||
queries.eventsByTag("green", new Sequence(0L));
|
||||
//#EventsByTag
|
||||
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 {
|
||||
|
||||
public
|
||||
// #tagger
|
||||
static class MyTaggingEventAdapter implements WriteEventAdapter {
|
||||
|
||||
@Override
|
||||
public Object toJournal(Object event) {
|
||||
|
|
@ -76,19 +75,17 @@ public class LeveldbPersistenceQueryDocTest {
|
|||
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);
|
||||
if (tags.isEmpty()) return event;
|
||||
else return new Tagged(event, tags);
|
||||
} else {
|
||||
return event;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public String manifest(Object event) {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
//#tagger
|
||||
// #tagger
|
||||
}
|
||||
|
|
|
|||
|
|
@ -27,10 +27,9 @@ import java.time.Duration;
|
|||
|
||||
import static java.util.stream.Collectors.toList;
|
||||
|
||||
//#events-by-tag-publisher
|
||||
// #events-by-tag-publisher
|
||||
class MyEventsByTagJavaPublisher extends AbstractActorPublisher<EventEnvelope> {
|
||||
private final Serialization serialization =
|
||||
SerializationExtension.get(getContext().getSystem());
|
||||
private final Serialization serialization = SerializationExtension.get(getContext().getSystem());
|
||||
|
||||
private final Connection connection;
|
||||
|
||||
|
|
@ -43,37 +42,44 @@ class MyEventsByTagJavaPublisher extends AbstractActorPublisher<EventEnvelope> {
|
|||
|
||||
private Cancellable continueTask;
|
||||
|
||||
public MyEventsByTagJavaPublisher(Connection connection,
|
||||
String tag,
|
||||
Long offset,
|
||||
Duration refreshInterval) {
|
||||
public MyEventsByTagJavaPublisher(
|
||||
Connection connection, String tag, Long offset, Duration 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().getDispatcher(), getSelf());
|
||||
this.continueTask =
|
||||
scheduler.schedule(
|
||||
refreshInterval,
|
||||
refreshInterval,
|
||||
getSelf(),
|
||||
CONTINUE,
|
||||
getContext().getDispatcher(),
|
||||
getSelf());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Receive createReceive() {
|
||||
return receiveBuilder()
|
||||
.matchEquals(CONTINUE, (in) -> {
|
||||
query();
|
||||
deliverBuf();
|
||||
})
|
||||
.match(Cancel.class, (in) -> {
|
||||
getContext().stop(getSelf());
|
||||
})
|
||||
.build();
|
||||
.matchEquals(
|
||||
CONTINUE,
|
||||
(in) -> {
|
||||
query();
|
||||
deliverBuf();
|
||||
})
|
||||
.match(
|
||||
Cancel.class,
|
||||
(in) -> {
|
||||
getContext().stop(getSelf());
|
||||
})
|
||||
.build();
|
||||
}
|
||||
|
||||
public static Props props(Connection conn, String tag, Long offset,
|
||||
Duration refreshInterval) {
|
||||
return Props.create(MyEventsByTagJavaPublisher.class, () ->
|
||||
new MyEventsByTagJavaPublisher(conn, tag, offset, refreshInterval));
|
||||
public static Props props(Connection conn, String tag, Long offset, Duration refreshInterval) {
|
||||
return Props.create(
|
||||
MyEventsByTagJavaPublisher.class,
|
||||
() -> new MyEventsByTagJavaPublisher(conn, tag, offset, refreshInterval));
|
||||
}
|
||||
|
||||
@Override
|
||||
|
|
@ -83,9 +89,10 @@ class MyEventsByTagJavaPublisher extends AbstractActorPublisher<EventEnvelope> {
|
|||
|
||||
private void query() {
|
||||
if (buf.isEmpty()) {
|
||||
final String query = "SELECT id, persistent_repr " +
|
||||
"FROM journal WHERE tag = ? AND id > ? " +
|
||||
"ORDER BY id LIMIT ?";
|
||||
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);
|
||||
|
|
@ -94,32 +101,35 @@ class MyEventsByTagJavaPublisher extends AbstractActorPublisher<EventEnvelope> {
|
|||
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)));
|
||||
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();
|
||||
buf =
|
||||
res.stream()
|
||||
.map(
|
||||
in -> {
|
||||
final Long id = in.first();
|
||||
final byte[] bytes = in.second();
|
||||
|
||||
final PersistentRepr p =
|
||||
serialization.deserialize(bytes, PersistentRepr.class).get();
|
||||
final PersistentRepr p =
|
||||
serialization.deserialize(bytes, PersistentRepr.class).get();
|
||||
|
||||
return new EventEnvelope(Offset.sequence(id), p.persistenceId(), p.sequenceNr(), p.payload());
|
||||
}).collect(toList());
|
||||
return new EventEnvelope(
|
||||
Offset.sequence(id), p.persistenceId(), p.sequenceNr(), p.payload());
|
||||
})
|
||||
.collect(toList());
|
||||
}
|
||||
} catch(Exception e) {
|
||||
onErrorThenStop(e);
|
||||
} catch (Exception e) {
|
||||
onErrorThenStop(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void deliverBuf() {
|
||||
while (totalDemand() > 0 && !buf.isEmpty())
|
||||
onNext(buf.remove(0));
|
||||
while (totalDemand() > 0 && !buf.isEmpty()) onNext(buf.remove(0));
|
||||
}
|
||||
}
|
||||
//#events-by-tag-publisher
|
||||
// #events-by-tag-publisher
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue