播放2.4 HTTP缓存(缓存)使非幂等请求无效(EhCache)

时间:2015-07-31 08:54:44

标签: caching playframework ehcache playframework-2.4

https://www.playframework.com/documentation/2.4.0/ScalaCache

我读过但没有说明如何使非幂等请求的Cached对象(HTTP缓存)无效。如果我们进行POST / PUT / DELETE,我们怎样才能使它无效?使用注入和缓存对象,我无法访问CacheApi对象(它包含删除方法)。

还有一个问题,如何处理控制器中的异步操作?

由于

编辑:示例代码。 FindById缓存响应。我想保留它,直到非幂等请求到达,如POST,然后在插入控制器方法中使缓存无效

@Inject() (val pushService: PushDbService, val cached: Cached)


def findById(id: String) = {
    val caching = cached
      .status(_ => "/pushes/findById"+ id, 200)
      .includeStatus(404, 60)

    caching {
      Action.async{
        pushService.findById(id).map{
          case Some(partner) => Ok(Json.toJson(partner))
          case None => NotFound
        }
      }
    }
  }


def insert() = Action.async(parse.json){ req =>
    req.body.validate[Push] match{
      case validatedPush: JsSuccess[Push] =>
        ***INVALIDATE CACHE HERE***
        pushService.insert(validatedPush.get).map{
          case Some(id) => Created(Json.toJson(id))
          case None => InternalServerError("Cannot insert object.")
        }
      case JsError(wrongPush) =>
        Future.successful(BadRequest("Body cannot be validated: "+wrongPush))
    }
  }

2 个答案:

答案 0 :(得分:1)

Cached只是helper,可以为Action添加缓存。它不包含任何remove方法。如果要更改缓存,请将CacheApi注入控制器。

@Inject()(val pushService: PushDbService, val cached: Cached, val cache: CacheApi)

使缓存无效:

cache.remove("/pushes/findById" + id)

请记住,您的操作是异步的。

答案 1 :(得分:0)

Mon Calamari的回复是有效的。我的代码片段:

def insert() = Action.async(parse.json){ req =>
    req.body.validate[Push] match{
      case validatedPush: JsSuccess[Push] =>
        pushService.insert(validatedPush.get).map{
          case Some(id) =>
            cache.remove(cacheKey)
            Created(Json.toJson(id))
          case None =>
            InternalServerError("Cannot insert object.")
        }
      case JsError(wrongPush) =>
        Future.successful(BadRequest("Body cannot be validated: "+wrongPush))
    }
  }

def findById(id: String) = Action.async{
    cache.get[Option[Push]](cacheKey+id) match{
      case Some(Some(value)) =>
        Future.successful(Ok(Json.toJson(value)))
      case Some(None) =>
        Future.successful(NotFound)
      case None =>
        pushService.findById(id).map{
          case Some(partner) =>
            cache.set(cacheKey+id,Some(partner))
            Ok(Json.toJson(partner))
          case None =>
            cache.set(cacheKey+id,None)
            NotFound
        }
    }
  }

非常感谢!!