Czy ktoś może wyjaśnić główne różnice między Akka HTTP i Netty? Netty oferuje również inne protokoły, takie jak FTP. Akka HTTP może być używany w Scala i Java i jest build on the actor model. Ale poza tym oba są asynchroniczne. Kiedy powinienem używać HTTP Akka i kiedy Netty? Jakie są typowe przypadki użycia dla obu?Różnice między Akka HTTP i Netty
Odpowiedz
Oto co widzę jako głównych obszarach contrastable:
Kodowanie stylu
Weźmy netty na discard server example który jest prawdopodobnie najprostszy przykład podano, że jest to pierwszy w dokumentacji.
Dla akka-http
ta jest stosunkowo prosta:
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)
}
Dla Netty jest to o wiele bardziej gadatliwy:
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();
}
}
Dyrektywy
Jednym z Akka HTTP największy mocnych, w moim opinia, to Directives, które zapewniają DSL dla skomplikowanej logiki obsługi żądań. Załóżmy na przykład, że chcemy odpowiedzieć jednym komunikatem dla żądań GET
i PUT
oraz kolejną wiadomością dla wszystkich innych metod żądań. Jest to bardzo łatwe przy użyciu dyrektyw:
val route =
(get | put) {
complete("You sent a GET or PUT")
} ~
complete("Shame shame")
, jeśli chcesz uzyskać element zamówienia i ilości od ścieżki żądanie:
val route =
path("order"/Segment/IntNumber) { (item, qty) =>
complete(s"Your order: item: $item quantity: $qty")
}
Funkcjonalność ta nie istnieje w ramach Netty.
Streaming
jeden ostatni element, chciałbym zwrócić uwagę jest to około streamingu. akka-http jest oparty na akka-stream
. Dlatego też, akka-http dobrze radzi sobie ze strumieniowaniem istot żądań. Weźmy przykład Looking Into the Received Data Netty jest dla Akka to wygląda
//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 muszą obsługiwać ten sam problem z buforami bajtowych i podczas pętli:
@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. Spring reaktor i netty vs tomcat http
- 2. Asynchroniczny klient HTTP z Netty
- 3. Różnice między BaseHttpServer i wsgiref.simple_server
- 4. błąd kompilacji Akka http
- 5. Różnice między Antsem i Maven
- 6. Różnice między SwingWorker i Executorem
- 7. Różnice między App.Config i Web.Config?
- 8. Różnice między .text i .get_text()
- 9. różnice między scipy.sparse.linalg.lsmr i scipy.sparse.linalg.lsqr
- 10. różnice między NSArray i CCArray
- 11. Różnice między MPI_Scatter i MPI_Bcast
- 12. Różnice między utf8 i latin1
- 13. Różnice między Smalltalk i python?
- 14. Różnice między ServletResponse i HttpServletResponseWrapper?
- 15. Różnice między .ContextMenu i .ContextMenuStrip
- 16. różnice między createRfcommSocketToServiceRecord i createRfcommSocket
- 17. Różnice między Boost.Coroutine i Boost.Coroutine2
- 18. Różnice między C: i C:/
- 19. Różnice między Sproutcore i Emberem
- 20. Różnice między setUp() i setUpBeforeClass()
- 21. Różnice między MySQLdb i mysqlconnector
- 22. Różnice między Coroutines i `goto`?
- 23. Różnice między JPA i JPA2
- 24. Akka HTTP Streaming JSON deserializacji
- 25. różnice między Msxml2.ServerXMLHTTP i WinHttp.WinHttpRequest?
- 26. Różnica między Java Współbieżność, Akka i RxJava?
- 27. Podobieństwa i różnice między PHPUnit i PHPSpec
- 28. Połączenie HTTP, różnice między Androidem 2.3 a 4
- 29. Serializacja - różnice między C++ i Javą
- 30. matplotlib Backend Różnice między Agg i Kair