Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Axon InMemory Eventstorage with ability to log the events
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.axonframework.eventhandling.TrackedEventMessage;
import org.axonframework.eventsourcing.eventstore.EmbeddedEventStore;
import org.axonframework.eventsourcing.eventstore.GlobalSequenceTrackingToken;
import org.axonframework.eventsourcing.eventstore.TrackingToken;
import org.axonframework.eventsourcing.eventstore.inmemory.InMemoryEventStorageEngine;
import java.lang.reflect.Field;
import java.util.NavigableMap;
import java.util.function.Supplier;
@Slf4j(topic = "eventStore")
@SuppressWarnings("unchecked")
public class EmbeddedInMemoryEventStore extends EmbeddedEventStore {
private static final InMemoryEventStorageEngine STORAGE_ENGINE = new InMemoryEventStorageEngine();
private final Supplier<NavigableMap<TrackingToken, TrackedEventMessage<?>>> events;
@SneakyThrows
public EmbeddedInMemoryEventStore() {
super(STORAGE_ENGINE);
final Field eventsField = InMemoryEventStorageEngine.class.getDeclaredField("events");
eventsField.setAccessible(true);
events = () -> {
try {
return (NavigableMap<TrackingToken, TrackedEventMessage<?>>) eventsField.get(STORAGE_ENGINE);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
};
}
public void log() {
final NavigableMap<TrackingToken, TrackedEventMessage<?>> map = events.get();
final StringBuilder b = new StringBuilder("EmbeddedInMemoryEventStore{events=");
for (TrackingToken t : map.navigableKeySet()) {
TrackedEventMessage<?> v = map.get(t);
b.append(String.format("\n\t[%03d] - %s",
((GlobalSequenceTrackingToken)t).getGlobalIndex(),
v.getPayload()
));
}
b.append("\n}");
log.info(b.toString());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment