Akka-HTTP和JAX-RS都是流行的用于构建RESTful服务的框架。下面是一个比较Akka-HTTP和JAX-RS的示例代码。
Akka-HTTP示例代码:
import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.server.Directives._
import akka.stream.ActorMaterializer
object AkkaHttpExample extends App {
implicit val system = ActorSystem("my-system")
implicit val materializer = ActorMaterializer()
implicit val executionContext = system.dispatcher
val route = path("hello") {
get {
complete("Hello, Akka-HTTP!")
}
}
val bindingFuture = Http().bindAndHandle(route, "localhost", 8080)
println(s"Server online at http://localhost:8080/")
}
JAX-RS示例代码:
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
@Path("/hello")
public class JaxRsExample {
@GET
@Produces(MediaType.TEXT_PLAIN)
public String hello() {
return "Hello, JAX-RS!";
}
public static void main(String[] args) throws Exception {
org.glassfish.jersey.server.ResourceConfig config = new org.glassfish.jersey.server.ResourceConfig();
config.register(JaxRsExample.class);
org.glassfish.jersey.jdkhttp.JdkHttpServerFactory.createHttpServer(URI.create("http://localhost:8080/"), config);
System.out.println("Server started");
}
}
这些示例代码分别使用Akka-HTTP和JAX-RS创建了一个简单的RESTful服务,监听在http://localhost:8080/hello
上,并返回相应的消息。
需要注意的是,Akka-HTTP使用Scala编写,而JAX-RS使用Java编写。
上一篇:akka-http 对于列表的 case class 的隐式 JSON 格式化
下一篇:akka-http web-app在最小化的Docker JRE 11上无法启动(为Scala 12 Akka-http需要哪些Java模块)?