0

我正在使用 Scala 2.10.2、Akka 2.2.0 并试图确定将现有 Java 类与 Actor 集成是否有意义。我想到的 Java 类是Apache Commons FileUpload 流 API

这就是我在不使用演员的情况下所做的工作

class HelloWorld extends HttpServlet {
  override def doGet(req: HttpServletRequest, resp: HttpServletResponse) = {
    resp.getWriter().print("Hello World!")
  }

  override def doPost(req: HttpServletRequest, resp: HttpServletResponse ) = {
    if (ServletFileUpload.isMultipartContent(req)) {
      val upload = new ServletFileUpload()

      // Parse the request
      val iter = upload.getItemIterator(req)
      while (iter.hasNext()) {
        val item = iter.next()
        val name = item.getFieldName()
        val stream = item.openStream()
        if (item.isFormField()) {
          println("Form field " + name + " with value " + Streams.asString(stream) + " detected.")
        } else {
          println("File field " + name + " with file name " + item.getName() + " detected.")
          saveAttachment(item.getName(), stream)
        }
      }
      resp.getWriter().print("\nFile uploads success!\n")
    } else
      resp.getWriter().print("\nNo file upload found!\n")
  }

  private def saveAttachment(...) {...}
}

通常,actor 在receive方法中处理其所有消息,但在这种情况下,该类已经具有预定义的方法。由于缺乏更好的术语,有没有办法实现这一点?我考虑的一个选项是创建一个actor来处理上传,doPost因为它是一个处理潜在大文件的阻塞调用。想法?

4

1 回答 1

0

如果有办法“制作”任何界面,我很想知道它。=) 在我看来,最简单的事情就是创建一个值,该值的行为类似于您可以向其发送消息的参与者,并将流处理实现拉入其中。所以,去掉重要的部分,它看起来像下面这样......

import akka.actor.ActorDSL._

class HelloWorld extends HttpServlet {

  val streamHandler = actor(new Act {
    become {
      case req: HttpServletRequest =>
        val upload = new ServletFileUpload()
        // ...
    }
  })

  override def doPost(req: HttpServletRequest, resp: HttpServletResponse) = {
    if (ServletFileUpload.isMultipartContent(req)) {
      streamHandler ! req
      resp.getWriter().print("\nFile uploads success!\n") // This is optimistic; we don't really know for sure
    } else {
      resp.getWriter().print("\nNo file upload found!\n")
    }
  }
}

当然,这是一种胶带解决方案;如果您向其发送除 HttpServletRequest 以外的任何其他内容,则该参与者会崩溃,这显然不是真正可重用的代码。它只是为了演示actor DSL。

于 2013-08-25T01:24:02.913 回答