Home > Java > javaTutorial > How does a Java function use NIO technology to handle high concurrent requests?

How does a Java function use NIO technology to handle high concurrent requests?

WBOY
Release: 2024-04-30 15:03:02
Original
538 people have browsed it

Java NIO is an efficient technology for handling high concurrent requests. It is implemented using non-blocking I/O and polling mechanisms: Create NIO Selector to listen for events; register Channel to Selector and listen for ACCEPT events; wait for events in a loop to process ACCEPT, READ and WRITE events; ACCEPT event handles client connection and creates SocketChannel; READ event reads data, and WRITE event writes data back.

Java 函数如何使用 NIO 技术处理高并发请求?

Java function uses NIO to handle high concurrent requests

Introduction
Non-blocking I/O (NIO) is an efficient technology in Java for handling large numbers of concurrent requests. It uses asynchronous operations and polling mechanisms to effectively utilize system resources and improve system throughput.

Steps
1. Create NIO Selector
NIO Selector is used to listen to events on the registered Channel.

Selector selector = Selector.open();
Copy after login

2. Register Channel
Register ServerSocketChannel to Selector and listen to ACCEPT event.

ServerSocketChannel serverChannel = ServerSocketChannel.open();
serverChannel.configureBlocking(false);
serverChannel.register(selector, SelectionKey.OP_ACCEPT);
Copy after login

3. Loop waiting for events
Listen to events through the Selector.select() method.

while (true) {
    selector.select();
    Set<SelectionKey> keys = selector.selectedKeys();
    // 处理事件...
}
Copy after login

4. Handle the ACCEPT event
When the ACCEPT event occurs, accept the connection and create a SocketChannel.

if (key.isAcceptable()) {
    ServerSocketChannel channel = (ServerSocketChannel) key.channel();
    SocketChannel clientChannel = channel.accept();
    clientChannel.configureBlocking(false);
    clientChannel.register(selector, SelectionKey.OP_READ);
}
Copy after login

Practical case
The following is a simple Java NIO Echo server example. It listens for client connections and echoes received messages.

EchoServer.java

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

public class EchoServer {

    private Selector selector;
    private ServerSocketChannel serverChannel;
    private int port;

    public EchoServer(int port) {
        this.port = port;
    }

    public void start() throws IOException {
        // 创建 Selector
        selector = Selector.open();

        // 创建 ServerSocketChannel
        serverChannel = ServerSocketChannel.open();
        serverChannel.configureBlocking(false);
        serverChannel.bind(new InetSocketAddress(port));
        serverChannel.register(selector, SelectionKey.OP_ACCEPT);

        // 不断循环等待事件
        while (true) {
            int keysCount = selector.select();
            if (keysCount == 0) {
                continue;
            }
            Set<SelectionKey> keys = selector.selectedKeys();
            for (SelectionKey key : keys) {
                try {
                    if (key.isAcceptable()) {
                        handleAccept(key);
                    } else if (key.isReadable()) {
                        handleRead(key);
                    } else if (key.isWritable()) {
                        handleWrite(key);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    key.cancel();
                    SocketChannel channel = (SocketChannel) key.channel();
                    channel.close();
                }
            }
            keys.clear();
        }
    }

    private void handleAccept(SelectionKey key) throws IOException {
        ServerSocketChannel channel = (ServerSocketChannel) key.channel();
        SocketChannel clientChannel = channel.accept();
        clientChannel.configureBlocking(false);
        clientChannel.register(selector, SelectionKey.OP_READ);
    }

    private void handleRead(SelectionKey key) throws IOException {
        SocketChannel channel = (SocketChannel) key.channel();
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        int readBytes = channel.read(buffer);
        if (readBytes == -1) {
            channel.close();
            return;
        }
        buffer.flip();
        channel.write(buffer);
    }

    private void handleWrite(SelectionKey key) throws IOException {
        SocketChannel channel = (SocketChannel) key.channel();
        channel.write(ByteBuffer.allocate(1024));
    }

    public static void main(String[] args) throws IOException {
        new EchoServer(9090).start();
    }
}
Copy after login

The above is the detailed content of How does a Java function use NIO technology to handle high concurrent requests?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template