简体   繁体   English

如何在Play Framework 2.x中实现隐式的Future的Json Writes of Future对象

[英]How to implement implicit Json Writes of Future object in Play Framework 2.x

I am new with play framework and i want to ask periodically to amazon about some products in order to insert them into a kafka topic, an error happens when i try to compile the code. 我是play框架的新手,我想定期向亚马逊询问一些产品,以便将它们插入kafka主题,当我尝试编译代码时会发生错误。

This is the code of the KafkaProducer: 这是KafkaProducer的代码:

file example.model.AmazonProducerExample 文件example.model.AmazonProducerExample

//UPDATED method with the suggestions from the users, thank you guys! // UPDATED方法结合用户的建议,谢谢大家!

package example.utils

import jodd.lagarto.dom.{NodeSelector, LagartoDOMBuilder}
import example.model.AmazonProduct
import scala.collection.JavaConversions._
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future

import play.api.libs.json._
import example.utils._
import example.producer._

object AmazonPageParser {

private val topicName = "amazonRatingsTopic"

private val producer = Producer[String](topicName)


def parse(productId: String): Future[AmazonProduct] = {

val url = s"http://www.amazon.com/dp/$productId"
HttpClient.fetchUrl(url) map {
  httpResponse =>
    if (httpResponse.getStatusCode == 200) {
      val body = httpResponse.getResponseBody
      val domBuilder = new LagartoDOMBuilder()
      val doc = domBuilder.parse(body)

      val responseUrl = httpResponse.getUri.toString
      val nodeSelector = new NodeSelector(doc)
      val title = nodeSelector.select("span#productTitle").head.getTextContent
      val img = nodeSelector.select("div#main-image-container img").head.getAttribute("src")
      val description = nodeSelector.select("div#feature-bullets").headOption.map(_.getHtml).mkString

      val amazonProduct = AmazonProduct(productId, title, responseUrl, img, description)

      println("amazonProduct is " + amazonProduct.toString)
      amazonProduct
    } else {
      println("An error happened!")
      throw new RuntimeException(s"Invalid url $url")
    }
}//map
}//parse method

def main(args: Array[String]): Unit = {

//Scala Puzzlers...
AmazonPageParser.parse("0981531679").onSuccess { case amazonProduct =>

  implicit val amazonFormat = Json.format[AmazonProduct]
  producer.send(Json.toJson(amazonProduct).toString)
  println("amazon product sent to kafka cluster..." + amazonProduct.toString)
}
}
}

file example.model.Models 文件example.model.Models

package example.model

import play.api.libs.json.Json
import reactivemongo.bson.Macros

case class AmazonProduct(itemId: String, title: String, url: String, img: String, description: String)
case class AmazonRating(userId: String, productId: String, rating: Double)

case class AmazonProductAndRating(product: AmazonProduct, rating: AmazonRating)

// For MongoDB
object AmazonRating {
implicit val amazonRatingHandler = Macros.handler[AmazonRating]
implicit val amazonRatingFormat = Json.format[AmazonRating]
}

file example.utils.AmazonPageParser 文件example.utils.AmazonPageParser

The compiler returns me this error: 编译器向我返回此错误:

[error] /Users/aironman/my-recommendation-spark-engine/src/main/scala/example/producer/AmazonProducerExample.scala:25: No Json serializer found for type scala.concurrent.Future[example.model.AmazonProduct]. Try to implement an implicit Writes or Format for this type.
[error]     producer.send(Json.toJson(amazonProduct).toString)
[error]                              ^

I have readed this post with most votes but it does not work for me. 我已以最多的票数阅读了帖子,但它对我不起作用。

Can anybody help me? 有谁能够帮助我?

Writes[T] produces Json. Writes[T]产生Json。 You can't produce it directly from Future without blocking. 您不能直接从Future生产它,而不能阻止它。

However you can add "callback" to this future, like this: 但是,您可以在此将来添加“回调”,如下所示:

amazonPageParser.parse(productId).onSuccess { case amazonProduct =>
   producer.send(Json.toJson(amazonProduct).toString)
}

Or with other Future methods, like map or foreach . 或使用其他Future方法,例如mapforeach

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM