Ошибка API Apala в Scala: ошибка сброса -Задержано время ожидания запроса [GET / mallet Empty] - PullRequest
0 голосов
/ 26 мая 2019

Прошу прощения, если вопрос звучит наивно, так как я довольно новичок в акке.

Я пытаюсь использовать API для Mallet в Scala Akka в остальных API Но при получении ошибки Тайм-аут запроса обнаружен

ниже приведен снимок моего Сервера

Configuration.parser.parse(args,Configuration.ConfigurationOptions()) match {
        case Some(config) =>
          val serverBinding: Future[Http.ServerBinding] = Http().bindAndHandle(routes, config.interface, config.port)
          serverBinding.onComplete {
            case Success(bound) =>
              println(s"Server online at http://${bound.localAddress.getHostString}:${bound.localAddress.getPort}/")
            case Failure(e) =>
              log.error("Server could not start: ", e)
              system.terminate()
          }
        case None =>
          system.terminate()
      }

      Await.result(system.whenTerminated, Duration.Inf)

снимок маршрутизатора

lazy val apiRoutes: Route =
    ignoreTrailingSlash {
      pathSingleSlash {
        complete(HttpEntity(ContentTypes.`text/html(UTF-8)`, "<html><body>Hello world!</body></html>"))
      } ~
        path("health") {
          complete(HttpEntity(ContentTypes.`text/html(UTF-8)`, "ok"))
        } ~
        pathPrefix("mallet") {
          parameter('malletFile) { malletFile =>
          {val modelFile: Future[MalletModel] =
            (malletActor ? GetMalletOutput(malletFile)).mapTo[MalletModel]
            complete(modelFile)
          }
          }
        }
    }

и, наконец, снимок MalletActor

class MalletActor(implicit val uaCache: Cache[String, MalletModel],
                  implicit val executionContext: ExecutionContext)
  extends Actor with ActorLogging with JsonSupport {

  import MalletActor._

  def receive: Receive = {
    case GetMalletOutput(malletFile) => sender() ! createMalletResult2(malletFile)
  }

  def createMalletResult2(malletFile: String): MalletModel = {

    logger.debug("run count...")
        val res = MalletResult(malletFile)
        val converted = res.Score.parseJson.convertTo[MalletRepo]
        val fileName = converted.ContentId

        val fileTemp = new File("src/main/resources/new_corpus/" + fileName)
        if (fileTemp.exists) {
          fileTemp.delete()
        }

        val output = new BufferedWriter(new FileWriter("src/main/resources/new_corpus/" + fileName))
        output.write(converted.ContentText)
        output.close()

    //runMalletInferring()

    val tmpDir = "src/main/resources/"
    logger.debug("Import all documents to mallet...")
    Text2Vectors.main(("--input " + tmpDir + "new_corpus/ --keep-sequence --remove-stopwords " + "--output " + tmpDir + "new_corpus.mallet --use-pipe-from " + tmpDir + "corpus.mallet").split(" "))
    logger.debug("Run training process...")
    InferTopics.main(("--input " + tmpDir + "new_corpus.mallet --inferencer " + tmpDir + "inferencer " + "--output-doc-topics " + tmpDir + "doc-topics-new.txt --num-iterations 1000").split(" "))
    logger.debug("Inferring process finished.")

Я получаю сообщение об ошибке при вызове text2Vector.main, новый векторизованный файл создается в каталоге new_corpus, а также генерируется new_corpus. однако после этого я получаю ошибку ниже

Server online at http://127.0.0.1:9000/
12:45:38.622 [Sophi-Mallet-Api-akka.actor.default-dispatcher-3] DEBUG io.sophi.api.mallet.actors.MalletActor$ - run count...
12:45:38.634 [Sophi-Mallet-Api-akka.actor.default-dispatcher-3] DEBUG io.sophi.api.mallet.actors.MalletActor$ - Import all documents to mallet...
Couldn't open cc.mallet.util.MalletLogger resources/logging.properties file.
 Perhaps the 'resources' directories weren't copied into the 'class' directory.
 Continuing.
May 26, 2019 12:45:38 PM cc.mallet.classify.tui.Text2Vectors main
INFO: Labels = 
May 26, 2019 12:45:38 PM cc.mallet.classify.tui.Text2Vectors main
INFO:    src/main/resources/new_corpus/
May 26, 2019 12:45:46 PM cc.mallet.classify.tui.Text2Vectors main
INFO:  rewriting previous instance list, with ID = 4e0a5a65540221c3:d508579:14b2ca15a26:-7ff7
[INFO] [05/26/2019 12:45:58.476] [Sophi-Mallet-Api-akka.actor.default-dispatcher-4] [akka.actor.ActorSystemImpl(Sophi-Mallet-Api)] Request timeout encountered for request [GET /mallet Empty]

в веб-браузере также появляется сообщение об ошибке

The server was not able to produce a timely response to your request.
Please try again in a short while!

1 Ответ

0 голосов
/ 27 мая 2019

Я сам разобрался с решением.Пожалуйста, поправьте меня, если оно все еще неясно.

Нужно было внести пару изменений.Сначала в файле конфигурации приложения (application.conf)

ниже код необходимо обновить.

server{
    idle-timeout = infinite
    request-timeout = infinite
}
settings {
  akka-workers-count = 100
  akka-workers-count = ${?AKKA_WORKERS_COUNT}
  actor-timeout = 100
  actor-timeout = ${?ACTOR_TIMEOUT}
}

И проблему необходимо решить в коде сервера, поместив вызов API в тайм-аутответ

  val timeoutResponse = HttpResponse(
    StatusCodes.EnhanceYourCalm,
    entity = "Running Mallet modelling.")

  lazy val apiRoutes: Route =
    ignoreTrailingSlash {
      pathSingleSlash {
        complete(HttpEntity(ContentTypes.`text/html(UTF-8)`, "<html><body>Hello world!</body></html>"))
      } ~
        path("health") {
          complete(HttpEntity(ContentTypes.`text/html(UTF-8)`, "ok"))
        } ~
        pathPrefix("mallet") {
          withRequestTimeout(5.minute, request => timeoutResponse) {
          parameter('malletFile) { malletFile => {
            val modelFile: Future[MalletModel] =
              (malletActor ? GetMalletOutput(malletFile)).mapTo[MalletModel]
            complete(modelFile)
          }
          }

          }
        }
    }
...