source: Dev/branches/play-2.0.1/documentation/manual/sandbox/Scalacache.md @ 322

Last change on this file since 322 was 322, checked in by hendrikvanantwerpen, 13 years ago

Added Play! framework and application with Jena dependency. Working on
the basic things now (login/register), after that start implementing
our data model.

File size: 1.5 KB
Line 
1# The Play cache API
2
3The default implementation of the Cache API uses EHCache. You can also provide your own implementation via a plug-in.
4
5# Accessing the Cache API
6The cache API is provided by the play.api.cache.Cache object. It requires a registered cache plug-in.
7
8> **Note:** The API is intentionally minimal to allow several implementation to be plugged. If you need a more specific API, use the one provided by your Cache plugin.
9
10Using this simple API you can either store data in cache:
11
12```
13Cache.set("item.key", connectedUser)
14```
15
16And then retrieve it later:
17
18```
19val maybeUser: Option[User] = Cache.getAs[User]("item.key")
20```
21
22There is also a convenient helper to retrieve from cache or set the value in cache if it was missing:
23
24```scala
25val user: User = Cache.getOrElse[User]("item.key") {
26  User.findById(connectedUser)
27}
28```
29
30How to remove the key is as follows.
31
32```
33// 2.0 final
34Cache.set("item.key", null, 0)
35// later
36Cache.remove("item.key")
37
38```
39
40# Caching HTTP responses
41
42You can easily create smart cached actions using standard Action composition.
43
44> **Note:** Play HTTP Result instances are safe to cache and reuse later.
45
46Play provides a default built-in helper for standard cases:
47
48```scala
49def index = Cached("homePage") {
50  Action {
51    Ok("Hello world")
52  }
53}
54```
55
56Or even:
57
58```scala
59def userProfile = Authenticated { user =>
60  Cached(req => "profile." + user) {     
61    Action {
62      Ok(views.html.profile(User.find(user)))
63    }   
64  }
65}
66```
67
68> **Next:** [[Calling WebServices | ScalaWS]]
Note: See TracBrowser for help on using the repository browser.