1. 程式人生 > >使用scala基於AKKA HTTP開發REST介面的簡單例項

使用scala基於AKKA HTTP開發REST介面的簡單例項

一般情況下會使用SpringMVC開發REST介面,但是公司主開發語言是scala,因此採用AKKA HTTP(spray已經不再維護)來開發REST介面,具體可參看官網文件:AKKA HTTP

本文依據官網開發REST介面,具體如下:

  • 開發環境:IDEA,MAVEN,SCALA

首先在pom.xml中新增依賴jar包:

    <dependency>
      <groupId>com.typesafe.akka</groupId>
      <artifactId>akka-http_2.12</artifactId>
      <version>10.1.3</version>
    </dependency>
    <dependency>
      <groupId>com.typesafe.akka</groupId>
      <artifactId>akka-stream_2.12</artifactId>
      <version>2.5.12</version> 
    </dependency>

編寫server端程式,如下:


import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.model._
import akka.http.scaladsl.server.Directives._
import akka.stream.ActorMaterializer

import scala.io.StdIn

/**
  * handle client requests as a RESTFUL server
  */
object WebServer {
  def main(args: Array[String]): Unit = {
    implicit val system = ActorSystem("api-server")
    implicit val materializer = ActorMaterializer()
    implicit val executionContext = system.dispatcher

    val route=path("hello"){
      get{
        complete(HttpEntity(ContentTypes.`text/html(UTF-8)`, "<h1>Say hello to akka-http</h1>"))
      }
    }
    val bingdingFuture = Http().bindAndHandle(route,"localhost",8080)
    StdIn.readLine()
    bingdingFuture.flatMap(_.unbind()).onComplete(_=>system.terminate())
  }

}

該服務端程式繫結本地的8080埠,處理"hello"請求,並將響應結果返回。執行該程式報錯:

java.lang.NoSuchMethodError: scala.Product.$init$(Lscala/Product;)V

scala版本不匹配,更改下pom.xmk中scala的版本(我從2.11.8改為2.12.6),再次執行,並在瀏覽器中輸入:

http://localhost:8080/hello

瀏覽器顯示:

表示響應結果已經成功返回!