akka-http的第一个小程序

package com.lightened.myproject
import akka.actor.ActorSystem
import akka.http.javadsl.server.Route
import akka.http.scaladsl.Http//http().bindandhandle
import akka.http.scaladsl.model.{ContentTypes, HttpEntity}
import akka.stream.ActorMaterializer
import scala.io.StdIn
import akka.http.scaladsl.model._
import akka.http.scaladsl.server.Directives._//path/get/complete
import akka.http.scaladsl.server.Directive0
import akka.http.scaladsl.server.Route

object WebServer {
  def main(args: Array[String]): Unit = {
    implicit val system = ActorSystem("my-system")
    implicit val materilizer = ActorMaterializer()
    implicit val executionContext = system.dispatcher

    lazy val route =
      path("register"){
        get {
          complete(HttpEntity(ContentTypes.`text/html(UTF-8)`, "

Welcome to register my project

")) } } val bindingFuture = Http().bindAndHandle(route,"localhost",8080) println(s"Server online at http://localhost:8080/\nPress RETURN to stop...") StdIn.readLine() bindingFuture //.flatMap(_.unbind()) .onComplete(_ => system.terminate()) } }

配置文件:

name := "My-first-akka-http-project"

version := "0.1"

scalaVersion := "2.12.4"
lazy val akkaHttpVersion = "10.0.11"
lazy val akkaVersion = "2.5.8"

lazy val root = (project in file("."))
  .settings(
    inThisBuild(List(
      organization :="com.example",
      scalaVersion :="2.12.4"
    )),
    name := "My-first-akka-http-project",
    libraryDependencies ++= Seq(
      "com.typesafe.akka" %% "akka-http"            % akkaHttpVersion,
      "com.typesafe.akka" %% "akka-http-spray-json" % akkaHttpVersion,
      "com.typesafe.akka" %% "akka-http-xml"        % akkaHttpVersion,
      "com.typesafe.akka" %% "akka-stream"          % akkaVersion,
    )

  )
terminal窗口输入sbt,然后输入compile,运行主函数文件,
Server online at http://localhost:8080/
Press RETURN to stop...
在浏览器输入http://localhost:8080/register

你可能感兴趣的:(Scala)