我使用scalacache
与memcache
使用以下依赖关系
libraryDependencies + =" com.github.cb372" %%" scalacache-memcached" %" 0.24.0"
使用here中的示例我能够存储简单的数据类型。在现有示例的范围内,我编写了以下代码来存储collection
个Person
个对象
final case class Person(id: Int, name: String, company: String) extends
Codec[Person]{
override def encode(value: Person): Array[Byte] =
new String(value.id+"|"+value.name+"|"+value.company).getBytes("utf-8")
override def decode(bytes: Array[Byte]): Codec.DecodingResult[Person] =
Codec.tryDecode(convertToPerson(bytes))
def convertToPerson(bytes: Array[Byte]) : Person = {
val str = new String(bytes, "utf-8")
val array: Array[String] = str.split("|")
Person.apply(array.apply(0).toInt, array.apply(1), array.apply(2))
}
}
我正试图以下列方式使用Person
来存储此memcache
课程
val personSeq = List(
Person(1, "Abc", "Xyz"),
Person(2, "Ghi", "Prq"),
Person(3, "Jkl", "Uvw")
)
implicit val cache = MemcachedCache("localhost:11211")
val inserted = put("people")(personSeq)
println(inserted.get)
val result = get("people")
val s = result.getOrElse("None")
println(s)
我在这里遇到以下错误。
Error:(38, 39) Could not find any Codecs for type V.
If you would like to serialize values in a binary format, please import the binary codec:
import scalacache.serialization.binary._
If you would like to serialize values as JSON using circe, please import the circe codec
and provide a circe Encoder[V] and Decoder[V], e.g.:
import scalacache.serialization.circe._
import io.circe.generic.auto._
You will need a dependency on the scalacache-circe module.
See the documentation for more details on codecs.
implicit val cache = MemcachedCache("localhost:11211")
Error:(38, 39) ambiguous implicit values:
both object IntBinaryCodec in trait BinaryPrimitiveCodecs of type scalacache.serialization.binary.package.IntBinaryCodec.type
and object DoubleBinaryCodec in trait BinaryPrimitiveCodecs of type scalacache.serialization.binary.package.DoubleBinaryCodec.type
match expected type scalacache.serialization.Codec[V]
implicit val cache = MemcachedCache("localhost:11211")
有关如何使用scala-cache将集合持久存储到memcache中的任何建议吗?
答案 0 :(得分:1)
您可以通过将Cache
类型变量设为集合来存储集合:
implicit val personSeqCache: Cache[List[Person]] = MemcachedCache("localhost:11211")
这对我有用,即使不必定义Codec[Person]
或Codec[List[Person]]
。当您import scalacache.serialization.binary._
时,根据this