我并不是指禁用 PlayNettyServer 并启用文档中描述的 AkkaHttpServer 的方式,方法是使用:
lazy val root = (project in file("."))
.enablePlugins(PlayScala, PlayAkkaHttpServer)
.disablePlugins(PlayNettyServer)
我的意思是利用 play 框架的依赖注入和其他工具,如 play-slick,并直接在代码中使用 akka-http,如:
class AppInitiation @Inject()(implicit val system: ActorSystem, configuration: Configuration) {
implicit val materializer = ActorMaterializer()
implicit val timeout: Timeout = 5 seconds
val logger = Logger("Server")
val milkywayPath = path(Segment ~ RestPath)
val methods = get | put | post | delete
val gatewayExceptionHandler = ExceptionHandler {
case e: AskTimeoutException =>
complete(HttpResponse(InternalServerError, Nil, "Ask timeout!"))
case e: Exception =>
logger.error("unknown error", e)
complete(HttpResponse(InternalServerError, Nil, "Unknown error! Please contact administratro!"))
}
implicit def rejectionHandler = RejectionHandler.newBuilder()
.handle { case MissingHeaderRejection("X-Caller-Service") =>
complete(HttpResponse(BadRequest, Nil, "Missing required header X-Caller-Service!"))
}
.handle { case MissingQueryParamRejection("v") =>
complete(HttpResponse(BadRequest, Nil, "Missing required parameter v!"))
}
.result()
val requestHandler = system.actorOf(Props(new RequestHandler))
val routes = handleExceptions(gatewayExceptionHandler) {
(milkywayPath & methods & parameter('v.as[String]) & headerValueByName("X-Caller-Service") & extractRequest) {
(contextPath: String, resource: Path, v, caller, request) =>
complete {
val startTime = System.currentTimeMillis()
val callerInfo = CallerInfo(caller, contextPath, v, resource.toString())
val f = (requestHandler ? RequestHandlerMsg(callerInfo, request)).mapTo[HttpResponse]
f onComplete {
case r => accessLogger.info(s"method=${request.method.name} " +
s"uri=${request.uri} " +
s"caller=$caller " +
s"totalTime=${System.currentTimeMillis() - startTime}ms " +
s"resultStatus=${r.map(_.status.intValue).getOrElse(500)}")
}
f
}
}
}
val host = configuration.getString("gateway.host").getOrElse("localhost")
val port = configuration.getInt("gateway.port").getOrElse(9001)
Http().bindAndHandle(routes, host, port).onComplete(_ => logger.info(s"Server started listening request on port $port"))
}
在模块中我可以将其设置为:
override def configure(): Unit = {
bind(classOf[AppInitiation]).asEagerSingleton()
}
这行得通。但我仍然想知道如何在不运行 PlayNettyServer 的情况下启动它。我试过了:
lazy val `root` = (project in file("."))
.enablePlugins(PlayScala)
.disablePlugins(PlayNettyServer)
但是出现了异常:
[info] p.a.l.c.ActorSystemProvider - Starting application default Akka system: application
play.core.server.ServerStartException: No ServerProvider configured with key 'play.server.provider'
at play.core.server.ServerProvider$$anonfun$1.apply(ServerProvider.scala:54)
at play.core.server.ServerProvider$$anonfun$1.apply(ServerProvider.scala:54)
我想知道是否有办法充分利用 Play 框架及其所有功能,并使用 akka http 构建更高性能的服务器。