如何从播放缓存中获取对象(标量) [英] How to get object from Play cache (scala)
问题描述
如何从Play缓存(标量)获取对象
How to get object from Play cache (scala)
要设置的代码:
play.api.cache.Cache.set("mykey98", new Product(98), 0)
要获取的代码:
val product1: Option[Any] = play.api.cache.Cache.get("mykey98")
我得到Option对象.如何获得第一步中存储的实际Product对象.
I get Option object. How to get actual Product object I stored in first step.
推荐答案
首先,我建议使用带有类型参数的Cache.getAs
.这样,您就不会被Option[Any]
所困扰.有几种方法可以做到这一点.在我的示例中,我将使用String
,但是它将与任何其他类相同.我的首选方式是通过模式匹配:
First and foremost, I would suggest using Cache.getAs
, which takes a type parameter. That way you won't be stuck with Option[Any]
. There are a few ways you can do this. In my example, I'll use String
, but it will work the same with any other class. My preferred way is by pattern matching:
import play.api.cache.Cache
Cache.set("mykey", "cached string", 0)
val myString:String = Cache.getAs[String]("mykey") match {
case Some(string) => string
case None => SomeOtherClass.getNewString() // or other code to handle an expired key
}
此示例在模式匹配方面有点过分简化,但是当需要根据键的存在来分支代码时,我认为它是一种更好的方法.您也可以使用Cache.getOrElse
:
This example is a bit over-simplified for pattern matching, but I think its a nicer method when needing to branch code based on the existence of a key. You could also use Cache.getOrElse
:
val myString:String = Cache.getOrElse[String]("mykey") {
SomeOtherClass.getNewString()
}
在特定情况下,将String
替换为Product
,然后更改代码以处理如果键不存在(例如设置默认键)会发生的情况.
In your specific case, replace String
with Product
, then change the code to handle what will happen if the key does not exist (such as setting a default key).
这篇关于如何从播放缓存中获取对象(标量)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!