I’ve been reading a lot lately about how people switch back from Scala to Ruby, since they often fail to adapt to the way of thinking required to make Scala or partially Liftweb scale to the level they want.
I will write a post about that phenomenon and what’s wrong with it a few weeks, still writing that particular piece :)
Anyway, the focus of this post is the LiftActor.
It is a lightweight concept adapted from Erlang’s Actors (Scala has Actors as well, just to mention it), but David Pollack drizzled a little bit of sugar on top.
So what about it?
In my passion project, i’ve come across a lot of listings which require fetching the same resource over and over again. Imagine a User-class with a MappedLongForeignKey for the reference to a Customer-class. If we had a listing of users with a Customer column, it would have to select every Customer again and again for every single User. Depending on the number of Users (or whatever object references your cached entity), this concept just looks stupid and like the waste of a lot of CPU-cycles to me.
Now for my concept, i simply overrode a def like this:
For simplicity (and since the Customer-table is not that big), i’ve taken the liberty of pre-caching all Customers in my LiftActor:
What does it do? On startup, i will call CustomerCache.init somewhere in Boot.scala to start preloading. You can either send a Customer to the Actor, so it will be stored, you can send a Long in order to get the desired customer, or you can send a CustomerAll which will give you all the Customers. I’ve also taken the liberty of adding roles to my User-class, so i can do ACLs pretty nice (as you can hopefully see). ;)
That’s not all, as a nice extension i’ve added a couple of methods to CustomerCache, so it can be used in Boot.scala’s SiteMap as seen here:
Now we’ve got one problem left, once a Customer gets changed, how does the cache get notified? Well this is pretty easy:
This might not make that much sense on a User-class, but i’ve had the pleasure of reducing page-render time from a 2k-Domain-Listing from ~4200ms to ~80ms. Now that’s what i call performance!
I know that this is not groundbreaking, but i hope this will help getting beginners/people coming from other languages to realize the potential and the possibilities you can have in Web-Development thanks to Actors.