Home  >  Article  >  Java  >  Java Reactor Reactor Pattern

Java Reactor Reactor Pattern

Guanhui
Guanhuiforward
2020-06-24 18:09:432063browse

Java Reactor Reactor Pattern

Reactor Reactor Pattern

So far, high-performance network programming cannot avoid reactions. device mode. Many famous server software or middleware are implemented based on the reactor mode, such as Nginx, Redis, and Netty.

The reactor pattern is a must-know and must-know pattern for high-performance network programming.

Introduction to Reactor

The reactor mode consists of two major roles: Reactor reactor thread and Handlers processor:

(1) Reactor Responsibilities of the reactor thread: Responsible for responding to IO events and distributing them to Handlers processors.

(2) Responsibility of Handlers processor: non-blocking execution of business processing logic.

From the above reactor mode definition, we can’t see anything magical about this mode. Of course, there are many versions of the reactor pattern, from simple to complex. According to the previous definition, it is just the simplest version.

Fatal flaw of multi-threaded OIO

In Java OIO programming, the first and most primitive network server program uses a while loop to continuously Monitor the port for new connections. If so, call a processing function to complete it. The sample code is as follows:

@Test
 public void client() throws IOException {
   Socket client = new Socket("127.0.0.1", 9999);
   Writer writer = new OutputStreamWriter(client.getOutputStream());
   writer.write("Hello World");
   writer.flush();
   writer.close();
   client.close();
 }
 
 @Test
 public void server() throws IOException {
   ServerSocket server = new ServerSocket(9999);
   while (true){
     Socket socket = server.accept();
     Reader reader = new InputStreamReader(socket.getInputStream());
     print(reader);
     reader.close();
     socket.close();
     server.close();
   }
 }

The biggest problem with this method is: if the handle (socket) of the previous network connection has not been processed, then the subsequent connection request It cannot be received, so all subsequent requests will be blocked, and the server's throughput will be too low. For servers, this is a serious problem.

Recommended tutorial: "Java"

The above is the detailed content of Java Reactor Reactor Pattern. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:jb51.net. If there is any infringement, please contact admin@php.cn delete