onsdag 7 april 2010

Actors in java with akka, cont persistence

Ok, maybe we want our messages to be stored in a database in case something goes wrong?
I will use redis, so you will need to setup a local redis server. this is very simple read more on redis homepage: http://code.google.com/p/redis/
if you prefer cassandra or any other nosql database akka supports (check http://doc.akkasource.org/persistence ) you simply have to change RedisStorage to your storage solution.

Adding storage is usually allot of work. or at least some work. in akka, it is trivial:

in your maven pom.xml add:
<dependency>
<groupid>se.scalablesolutions.akka</groupId>
<artifactid>akka-persistence-redis_2.8.0.Beta1</artifactId>
<version>0.8</version>
</dependency>
this will include the dependencies we need to store everything.

in Chatserver.java


@transactionrequired
public class ChatServer {
    @Inject
    public ChatServer() {
    }
    private List<Message> messages = new ArrayList<Message>();
    private Set<ChatSession> sessions = new HashSet<ChatSession>();
    private PersistentVector<byte[]> storage;

    @inittransactionalstate
    public void init() {
        storage = RedisStorage.getVector("Storage");
    }


this is what changed:
i added an @transactionrequired annotation to the class, this means that all methods in ChatServer will be done in a stm transaction. you can read more about that in the akka docs: http://doc.akkasource.org/transactors

Then i changed the Vector to a PersistentVector. this is a datatype provided by akka, that stores its content in a database. There are several databases supported, Cassandra and redis are two examples. they all work with the same Peristent Datastructures, in addition to Vector there are for ex: PersistentMap and PersistentQueue.

I initiate this Vector in a method with the @inittransactionalstate annotation, this method should be called by magic by akka, but its currently not. so until a very near future when that is fixed, i decided to call that method in the login method in ChatSession.

Thats it, our messages are now stored in a redis database. if you installed redis with default settings, and use the default config for akka, it will find the database without any configuration.

Inga kommentarer:

Skicka en kommentar