I'm mostly talking about databases and cache in the context of a Play! app on Heroku:
What does the cache do for a database and how do I use it?
A cache is used to avoid querying a database too much.
Some queries take an especially long time to run. By caching the result (eg. saving it in memory), the expensive query doesn't need to be executed again (for a period of time when the data is still valid - where validity might be a few minutes, or until some data in a certain table changes).
A cache is normally just implemented as a giant hash table, will keys and values. The key is used to look-up a value.
The cache usage is described by http://www.playframework.org/documentation/2.0/ScalaCache. It is very easy to write the code for it. To store something in cache:
Cache.set("item.key", connectedUser)
Here you just pass the key to store the object at, and the object.
To retrieve it:
val user: User = Cache.getOrElseAs[User]("item.key") {
User.findById(connectedUser)
}
Basically, getOrElseAs[class to cast data to here](key here).
Notice the block you can pass to getOrElseAs
, so that if it is not found, you can query the database.
Otherwise, you can also use Cache.getAs[User]("item.key")
(but you probably want to query anyways if it isn't found).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With