Persistence - MongoDB

To persist the state of an actor, this must be derived from the PersistentActor class. A PersistentActor is characterized by events and a state, which can be saved, depending on the use case. In the example below, two events are defined. First, a snapshot of the state is made and persisted. Then the two events are saved. Handlers are defined for error handling and a successful case. After successfully saving the events, the actor’s state can be updated. Side effects can be triggered, which may affect other actors. The recover method is called to recover the actor’s state. It is loaded from the database, where the last state and the last events have persisted. With the help of the Recovery class, these attributes can be loaded. For this purpose, the JSON String will be transformed into a Recovery object. The principles of Event Sourcing [1] are followed, as a database MongoDB [2] is currently used. Every PersistentActor must have a persistent UUID for unique access. [3]

public class MyActor extends PersistentActor<MyState, MyEvent> {
	@Override
	public void receive(ActorMessage<?> message) {
    	// two events are generated based on the received message (!)
		MyEvent event1 = new MyEvent("I am the first event!");
		MyEvent event2 = new MyEvent("I am the second event!");
		
        // the events will be persisted
		persist(
			(s) -> logger().debug(String.format("Event: %s", s)), 
			(e) -> logger().error(String.format("Error: %s", e.getMessage())),
			event1, event2);		
            
        // the state will be persisted
        saveSnapshot(null, null, new MyState("I am a state!"));
	}
    
    @Override
	public void recover(JsonObject value) {
		if (!Recovery.isError(value)) {
			Recovery<MyState, MyEvent> obj = Recovery.convertValue(value, 
           		new GenericType<Recovery<MyState, MyEvent>>(){});
			logger().debug(String.format("Recovery: %s", obj.toString()));
		}
		else
			logger().error(String.format("Error: %s", Recovery.getErrorMsg(value)));
	}
			
	@Override
	public UUID persistenceId() {
		return UUID.fromString("60f086af-27d3-44e9-8fd7-eb095c98daed");
	}
}		            

References

[1] Martin Fowler (2005). Event Sourcing. http://martinfowler.com/eaaDev/EventSourcing.html
[2] MongoDB Inc (2016). MongoDB. https://www.mongodb.com/
[3] Lightbend (2015). Persistence. http://doc.akka.io/docs/akka/2.4/java/persistence.html