播放2.2 Scala类可序列化缓存

时间:2013-12-10 07:26:57

标签: scala serialization ehcache playframework-2.1 playframework-2.2

我有一个来自play-mongojack示例的scala类。它工作正常。但是,当我尝试将其保存在Play ehcache中时,它会抛出NotSerializableException。如何使这个类可序列化?

class BlogPost(@ObjectId @Id val id: String,
             @BeanProperty @JsonProperty("date") val date: Date,
             @BeanProperty @JsonProperty("title") val title: String,
             @BeanProperty @JsonProperty("author") val author: String,
             @BeanProperty @JsonProperty("content") val content: String) {
                 @ObjectId @Id @BeanProperty var blogId: String = _
                 @BeanProperty @JsonProperty("uploadedFile") var uploadedFile: Option[(String, String, Long)] =  None
}

object BlogPost {
   def apply(
       date: Date,
       title: String,
       author: String,
       content: String): BlogPost = new BlogPost(date,title,author,content)

   def unapply(e: Event) =
       new Some((e.messageId,
          e.date,
          e.title,
          e.author,
          e.content,
          e.blogId,
          e.uploadedFile) )

    private lazy val db = MongoDB.collection("blogposts", classOf[BlogPost], classOf[String])

    def save(blogPost: BlogPost) { db.save(blogPost) }
    def findByAuthor(author: String) = db.find().is("author", author).asScala
}

保存到缓存:

var latestBlogs  = List[BlogPost]()
Cache.set("latestBlogs", latestBlogs, 30)

它抛出异常:

[error] n.s.e.s.d.DiskStorageFactory - Disk Write of latestBlogs failed:
java.io.NotSerializableException: BlogPost
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1183) ~[na:1.7.0_45]
    at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:347) ~[na:1.7.0_45]
    at java.util.ArrayList.writeObject(ArrayList.java:742) ~[na:1.7.0_45]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.7.0_45]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) ~[na:1.7.0_45]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.7.0_45]

编辑1: 我尝试使用Serializable扩展对象,但它不起作用。

object BlogPost extends Serializable {}

编辑2: vitalii的评论对我有用。

class BlogPost() extends scala.Serializable {}

1 个答案:

答案 0 :(得分:1)

尝试从BlogPost派生类Serializable或将其定义为默认情况下可序列化的案例类。