使用scala基于AKKA HTTP开发REST接口的简单实例

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/javajxz008/article/details/81478764

一般情况下会使用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

浏览器显示:

表示响应结果已经成功返回!

猜你喜欢

转载自blog.csdn.net/javajxz008/article/details/81478764
今日推荐