Reactive Programming with RxJava-Chapter5:Reactive from Top to Bottom(1)

    xiaoxiao2021-03-25  104

    Beating the C10k Problem

    Traditional Thread-Based HTTP Servers

    Single threaded server

    Traditional applications are inherently limited to a couple thousand connections,even built on top of modern servlet containers

    Nonblocking HTTP Server with Netty and RxNetty

    Netty is entirely event-driven;we never block waiting for data to be sent ir received.Instead,raw bytes in the form of ByteBuf instances are pushed to our processing pipeline.Whenever a few bytes arrive to our application,Netty will notify our handler.Whenever we send few bytes,we get a ChannelFuture without blocking.

    Netty uses just a handful of threads to process possibly thousands of connections.We do not keep any heavyweight data structures or threads per each connection.

    Observable server with RxNetty

    HttpServer .newServer(8080) .start((req,resp)) -> { String amountStr = req.getDecodedPath().substring(1); BigDecimal amount = new BigDecimal(amountStr); Observable<String> response = Observable .just(amount) .map(eur -> eur.multiply(RATE)) .map(usd -> "{\"EUR\": " + amount +"," + "\"USD\": " + isd + "}"); return resp.writeString(response); }) .awaitShutdown();

    This implementation can easily withstand thousands of concurrent connections,and vertical scalability is limited only by the amount of traffic it must handle,not the number of more-or-less idle connections.

    Reactive HTTP Servers Tour

    Http Client Code

    A TCP/IP connection is actually quite lightweight.The operating system must keep a socket descriptor for each open connection (around one kb) and that is pretty much it.When a packet (messages) arrives,the kernel dispatches it to the appropriate process,like JVM.One kb is quite a small memory footprint compared to the roughly one mb consumed by the stack of each thread blocked on a socket.

    Nonblocking HTTP Client with RxNetty

    RxNetty goes a bit futrher compared to other nonblocking HTTP clients and does not simply notify us when the entrie response arrives.Instead,we get a stream of ByteBuf messages,optionally followed by Observable completion when the server decides to drop the connection.

    最后,安利一款自己写的基于MVP的Android开发框架 https://github.com/sxenon/Pure 欢迎大家拍砖,如果觉得好,麻烦多多star

    转载请注明原文地址: https://ju.6miu.com/read-24917.html

    最新回复(0)