The Play cache API

Play 缓存 API

使用EHCache为缓存API的默认实现.你同时可以通过一个插件来提供你自己的实现。

载入缓存API

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

  1. libraryDependencies ++= Seq(
  2. cache,
  3. ...
  4. )

访问缓存API

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

  1. 注意: API有意的最小化允许多种实现可被嵌入。如果你需要一个更具体的API,使用你的缓存插件提供的那一个。

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

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

并在不久后获取它:

  1. val maybeUser: Option[User] = Cache.getAs[User]("item.key")

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

  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")

缓存HTTP回应

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

  1. 注意: Play HTTP 结果实例对缓存是安全的并可以之后从用。

Play为默认的例子提供了一个默认的嵌入帮助器:

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

甚至于:

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

缓存控制

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

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

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

或者“缓存404未找到”的信息仅存在几分钟

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