玩2.4 HTTP缓存(Cached)对于非幂等请求无效(EhCache)

Play 2.4 HTTP Cache (Cached) invalidate for non idempotent requests (EhCache)

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

Cached 只是一个 helper 来为 Action 添加缓存。它不包含任何 remove 方法。如果您想更改缓存,请将 CacheApi 注入您的控制器。

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

并使缓存失效:

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

请记住,您的操作是异步的。一旦 Future 被赎回,set/remove 缓存条目就有意义了。

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
        }
    }
  }

非常感谢!!