akka-http的第一个小程序

本文档引导读者通过配置文件初始化一个Akka-HTTP的小程序,涵盖了基本的设置和启动流程,旨在帮助初学者快速上手Akka-HTTP框架。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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)`, "<h1>Welcome to register my project</h1>"))
        }
      }
    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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值