The Play cache API

    Add cache into your dependencies list. For example, in build.sbt:
    将cache加入到你的关联列表中。例如,在build.sbt中:

    play.api.cache.Cache对象提供了缓存API.其需要一个注册的缓存插件。

    使用这个简单的API你既可以存储数据于缓存中:

    1. Cache.set("item.key", connectedUser)

    当其不存在时候这里还有一个简洁的帮助器去从缓存中获取或在缓存中设定值:

    1. val user: User = Cache.getOrElse[User]("item.key") {
    2. User.findById(connectedUser)
    3. }

    To remove an item from the cache use the remove method:
    使用remove方法去从缓存中移除一个条目:

    1. Cache.remove("item.key")

    你可以使用标准的Action组合。

    1. def index = Cached("homePage") {
    2. Ok("Hello world")
    3. }
    4. }

    甚至于:

    1. user =>
    2. Cached(req => "profile." + user) {
    3. Action {
    4. Ok(views.html.profile(User.find(user)))
    5. }
    6. }
    7. }

    你可以简单的控制什么是你想缓存的或者什么是你不想缓存的。

    你可能仅需要结果为“缓存200 OK”

    1. def get(index: Int) = {
    2. .status(_ => "/resource/"+ index, 200)
    3. caching {
    4. Action {
    5. if (index % 2 == 1) {
    6. Ok(Json.obj("id" -> index))
    7. } else {
    8. NotFound
    9. }
    10. }
    11. }