如何使用scala-cache API将对象集合存储到memcache中

时间:2018-04-27 12:32:41

标签: scala memcached

我使用scalacachememcache使用以下依赖关系

libraryDependencies + =" com.github.cb372" %%" scalacache-memcached" %" 0.24.0"

使用here中的示例我能够存储简单的数据类型。在现有示例的范围内,我编写了以下代码来存储collectionPerson个对象

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中的任何建议吗?

1 个答案:

答案 0 :(得分:1)

您可以通过将Cache类型变量设为集合来存储集合:

    implicit val personSeqCache: Cache[List[Person]] = MemcachedCache("localhost:11211")

这对我有用,即使不必定义Codec[Person]Codec[List[Person]]。当您import scalacache.serialization.binary._时,根据this

,Java序列化用于对任何对象进行编码