标签:
AKKa 版的httpServer
官方文档:http://akka.io/docs/?_ga=1.258204936.386978128.1439703494
在maven中添加下面依赖:
<dependencies> <dependency> <groupId>com.typesafe.akka</groupId> <artifactId>akka-stream-experimental_2.11</artifactId> <version>1.0</version> </dependency> <dependency> <groupId>com.typesafe.akka</groupId> <artifactId>akka-http-core-experimental_2.11</artifactId> <version>1.0</version> </dependency> <dependency> <groupId>com.typesafe.akka</groupId> <artifactId>akka-http-experimental_2.11</artifactId> <version>1.0</version> </dependency> </dependencies>
使用下面代码构建HTTPServer:
import akka.actor.ActorSystem import akka.stream.ActorMaterializer import akka.stream.scaladsl.Sink import akka.http.scaladsl.Http import akka.http.scaladsl.model.HttpMethods._ import akka.http.scaladsl.model._ import scala.concurrent.Future object HttpServer extends App { implicit val system = ActorSystem() implicit val materializer = ActorMaterializer() val serverSource = Http().bind(interface = "localhost", port = 8080) val requestHandler: HttpRequest => HttpResponse = { case HttpRequest(GET, Uri.Path("/"), _, _, _) => HttpResponse(entity = HttpEntity(MediaTypes.`text/html`, "<html><body>Hello world!</body></html>")) case HttpRequest(GET, Uri.Path("/ping"), _, _, _) => HttpResponse(entity = "PONG!") case HttpRequest(GET, Uri.Path("/crash"), _, _, _) => sys.error("BOOM!") case _: HttpRequest => HttpResponse(404, entity = "Unknown resource!") } val bindingFuture: Future[Http.ServerBinding] = serverSource.to(Sink.foreach { connection => println("Accepted new connection from " + connection.remoteAddress) connection handleWithSyncHandler requestHandler // this is equivalent to // connection handleWith { Flow[HttpRequest] map requestHandler } }).run() }
标签:
原文地址:http://www.cnblogs.com/qugangf/p/4734554.html