有人可以解释一下Akka HTTP和Netty之间的主要区别吗? Netty还提供其他协议,如FTP。 Akka HTTP可以在Scala和Java中使用,并且是build on the actor model。但除此之外,两者都是异步的。什么时候我会使用Akka HTTP和Netty?两者的典型用例是什么?
答案 0 :(得分:4)
以下是我认为的主要可比区域:
编码样式
让我们来看看netty的discard server example,这可能是最简单的例子,因为它是文档中的第一个。
对于akka-http
,这相对简单:
object WebServer {
def main(args: Array[String]) {
implicit val system = ActorSystem("my-system")
implicit val materializer = ActorMaterializer()
val route =
extractRequestEntity { entity =>
onComplete(entity.discardBytes(materializer)) { _ =>
case _ => complete(StatusCodes.Ok)
}
}
val bindingFuture = Http().bindAndHandle(route, "localhost", 8080)
}
对于netty来说,这更加冗长:
public class DiscardServerHandler extends ChannelInboundHandlerAdapter { // (1)
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) { // (2)
// Discard the received data silently.
((ByteBuf) msg).release(); // (3)
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { // (4)
// Close the connection when an exception is raised.
cause.printStackTrace();
ctx.close();
}
}
public class DiscardServer {
private int port;
public DiscardServer(int port) {
this.port = port;
}
public void run() throws Exception {
EventLoopGroup bossGroup = new NioEventLoopGroup(); // (1)
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap b = new ServerBootstrap(); // (2)
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class) // (3)
.childHandler(new ChannelInitializer<SocketChannel>() { // (4)
@Override
public void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new DiscardServerHandler());
}
})
.option(ChannelOption.SO_BACKLOG, 128) // (5)
.childOption(ChannelOption.SO_KEEPALIVE, true); // (6)
// Bind and start to accept incoming connections.
ChannelFuture f = b.bind(port).sync(); // (7)
// Wait until the server socket is closed.
// In this example, this does not happen, but you can do that to gracefully
// shut down your server.
f.channel().closeFuture().sync();
} finally {
workerGroup.shutdownGracefully();
bossGroup.shutdownGracefully();
}
}
public static void main(String[] args) throws Exception {
new DiscardServer(8080).run();
}
}
<强>指令强>
在我看来,akka-http的最大优势之一是Directives,它为复杂的请求处理逻辑提供了DSL。例如,假设我们想要响应GET
和PUT
请求的一条消息以及所有其他请求方法的另一条消息。使用Directives非常容易:
val route =
(get | put) {
complete("You sent a GET or PUT")
} ~
complete("Shame shame")
如果您想从请求路径获取订单商品和数量:
val route =
path("order" / Segment / IntNumber) { (item, qty) =>
complete(s"Your order: item: $item quantity: $qty")
}
netty中不存在此功能。
<强>流强>
我要注意的最后一项是流媒体。 akka-http基于akka-stream
。因此,akka-http很好地处理了请求实体的流媒体特性。以netty的Looking Into the Received Data为例,对于akka,这看起来像是
//a stream with a Source, intermediate processing steps, and a Sink
val entityToConsole : (RequestEntity) => Future[Done] =
(_ : RequestEntity)
.getDataBytes()
.map(_.utf8String)
.to(Sink.foreach[String](println))
.run()
val route =
extractRequestEntity { entity =>
onComplete(entityToConsole(entity)) { _ =>
case Success(_) => complete(200, "all data written to console")
case Failure(_) => complete(404, "problem writing to console)
}
}
Netty必须处理字节缓冲区和while循环的相同问题:
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
ByteBuf in = (ByteBuf) msg;
try {
while (in.isReadable()) { // (1)
System.out.print((char) in.readByte());
System.out.flush();
}
} finally {
ReferenceCountUtil.release(msg); // (2)
}
}
答案 1 :(得分:2)
Akka HTTP Server是具有高级DSL的HTTP和WebSocket服务器。 Netty是一个低级的“异步事件驱动的网络应用程序框架”,可以实现所需的任何TCP / UDP协议。
因此,除非需要一些底层网络,否则不应该使用纯Netty。使用Netty的Akka HTTP等效项将类似于Netty Reactor,而在它们之上的更高级别可能类似于Spring WebFlux。
另一方面,Akka-HTTP基于Akka Actors,这是一个建议特定应用程序模型的框架。另外,Akka依赖于Scala,如果您已经知道Scala或在调试应用程序时不准备学习Scala,这可能会影响决策。