Table of Contents
Preface
核心类
ConnectionCtx
Worker
运行一个简单的 Web 服务器
总结
Home Java javaTutorial Getty-Detailed explanation of implementing Java NIO framework design

Getty-Detailed explanation of implementing Java NIO framework design

Mar 24, 2017 am 10:46 AM

Preface

Getty is a NIO framework I wrote to learn Java NIO. During the implementation process, I referred to the design of Netty and used Groovy to implement it. Although it is just a toy, the sparrow is small and has all the internal organs. During the implementation process, I not only became familiar with the use of NIO, but also learned a lot of Netty's design ideas, improving my coding and design capabilities.

As for why I use Groovy to write it, because I just learned Groovy and just used it to practice. In addition, Groovy is compatible with Java, so the difference is only in syntax. The underlying implementation is still based on Java APIof.

Getty’s core code lines do not exceed 500 lines. On the one hand, it benefits from Groovy’s concise syntax, and on the other hand, because I only implemented the core logic. The most complicated thing is actually the decoder implementation. Scaffolding is easy to build, but building a skyscraper is not that easy, but it is enough for learning NIO.

ThreadingModel

Getty uses Reactor multi-threaded model

Getty-Detailed explanation of implementing Java NIO framework design

  1. ##There is a dedicated NIO thread - the Acceptor thread is used to monitor the server, receive the client's TCP connection request, and then assign the connection to the worker thread, which monitors the read and write

    Getty-Detailed explanation of implementing Java NIO framework designs .

  2. Network IO operations - reading/writing, etc. are responsible for multiple worker threads, and these worker threads are responsible for reading, decoding, encoding and sending messages.

  3. 1 worker thread can process N links at the same time, but 1 link only corresponds to 1 worker thread to prGetty-Detailed explanation of implementing Java NIO framework design concurrent operation problems.

Event-driven model

The entire server-side process processing is based on the Getty-Detailed explanation of implementing Java NIO framework design mechanism. In the process of [Accept connection -> Read -> Business processing -> Write -> Close connection], the

trigger will trigger the corresponding Getty-Detailed explanation of implementing Java NIO framework design, and the Getty-Detailed explanation of implementing Java NIO framework design handler will handle the corresponding Getty-Detailed explanation of implementing Java NIO framework design respectively. Response to complete the server-side business processing.

Event definition

  1. onRead: This Getty-Detailed explanation of implementing Java NIO framework design is triggered when the client sends data and has been correctly read by the worker thread. This Getty-Detailed explanation of implementing Java NIO framework design notifies each Getty-Detailed explanation of implementing Java NIO framework design handler that the data sent by the client can be actually processed.

  2. onWrite: This Getty-Detailed explanation of implementing Java NIO framework design is triggered when the client can start to accept data sent by the server. Through this Getty-Detailed explanation of implementing Java NIO framework design, we can send response data to the client. (Write Getty-Detailed explanation of implementing Java NIO framework designs are not used in the current implementation)

  3. onClosed: This Getty-Detailed explanation of implementing Java NIO framework design is triggered when the client disconnects from the server.

Implementation of Getty-Detailed explanation of implementing Java NIO framework design callback mechanism

In this model, Getty-Detailed explanation of implementing Java NIO framework designs are broadcast, that is, all registered Getty-Detailed explanation of implementing Java NIO framework design handlers can receive Getty-Detailed explanation of implementing Java NIO framework design notifications. In this way, business processing of different natures can be implemented using different processors, making the function of each processor as single as possible.

As shown below: The entire Getty-Detailed explanation of implementing Java NIO framework design model consists of listeners, Getty-Detailed explanation of implementing Java NIO framework design adapters, Getty-Detailed explanation of implementing Java NIO framework design triggers (HandlerChain, PipeLine), and Getty-Detailed explanation of implementing Java NIO framework design processors.

Getty-Detailed explanation of implementing Java NIO framework design

  • ##ServerListener

    : This is an Getty-Detailed explanation of implementing Java NIO framework designinterface, which defines the server Getty-Detailed explanation of implementing Java NIO framework designs to be listened to

  • EventAdapter

    : Implement an adapter (EventAdapter) for the Serverlistener interface. The advantage of this is that the final Getty-Detailed explanation of implementing Java NIO framework design processor can only handle the Getty-Detailed explanation of implementing Java NIO framework designs of concern. <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class='brush:php;toolbar:false;'>class EventAdapter implements ServerListener { //下个处理器的引用 protected next void onRead(Object ctx) { } void onWrite(Object ctx) { } void onClosed(Object ctx) { } }</pre><div class="contentsignin">Copy after login</div></div>

  • Not

    ifier<a href="http://www.php.cn/wiki/109.html" target="_blank">: Used to notify the registered Getty-Detailed explanation of implementing Java NIO framework design handler to respond to the Getty-Detailed explanation of implementing Java NIO framework design by triggering server Getty-Detailed explanation of implementing Java NIO framework designs at the appropriate time. response. </a><div class="code" style="position:relative; padding:0px; margin:0px;"><pre class='brush:php;toolbar:false;'>interface Notifier extends Serializable{ /** * 触发所有可读事件回调 */ void fireOnRead(ctx) /** * 触发所有可写事件回调 */ void fireOnWrite(ctx) /** * 触发所有连接关闭事件回调 */ void fireOnClosed(ctx) }</pre><div class="contentsignin">Copy after login</div></div>

  • HandlerChain

    : Implements the Notifier interface to maintain an orderly Getty-Detailed explanation of implementing Java NIO framework design handler chain, starting from the first handler each time trigger. <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class='brush:php;toolbar:false;'>class HandlerChain implements Notifier{ EventAdapter head EventAdapter tail /** * 添加处理器到执行链的最后 * @param handler */ void addLast(handler) { if (tail != null) { tail.next = handler tail = tail.next } else { head = handler tail = head } } void fireOnRead(ctx) { head.onRead(ctx) } void fireOnWrite(ctx) { head.onWrite(ctx) } void fireOnClosed(ctx) { head.onClosed(ctx) } }</pre><div class="contentsignin">Copy after login</div></div>

  • PipeLine

    : Implements the Notifier interface as an Getty-Detailed explanation of implementing Java NIO framework design bus to maintain a list of Getty-Detailed explanation of implementing Java NIO framework design chains. <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class='brush:php;toolbar:false;'>class PipeLine implements Notifier{ static logger = LoggerFactory.getLogger(PipeLine.name) //监听器队列 def listOfChain = [] PipeLine(){} /** * 添加监听器到监听队列中 * @param chain */ void addChain(chain) { synchronized (listOfChain) { if (!listOfChain.contains(chain)) { listOfChain.add(chain) } } } /** * 触发所有可读事件回调 */ void fireOnRead(ctx) { logger.debug(&quot;fireOnRead&quot;) listOfChain.each { chain -&gt; chain.fireOnRead(ctx) } } /** * 触发所有可写事件回调 */ void fireOnWrite(ctx) { listOfChain.each { chain -&gt; chain.fireOnWrite(ctx) } } /** * 触发所有连接关闭事件回调 */ void fireOnClosed(ctx) { listOfChain.each { chain -&gt; chain.fireOnClosed(ctx) } } }</pre><div class="contentsignin">Copy after login</div></div>

  • Event processing process

Getty-Detailed explanation of implementing Java NIO framework designProgramming model

Event processing adopts the chain of responsibility model, each processor After processing the data, it is decided whether to continue executing the next processor. If the processor does not hand over the task to the thread pool for processing, then the entire processing process is processed in the same thread. And each connection has a separate

PipeLine

. The worker thread can switch between multiple connection contexts, but one connection context will only be processed by one thread. <h2 id="核心类">核心类</h2><h3 id="ConnectionCtx">ConnectionCtx</h3><p>连接上下文<code>ConnectionCtx

class ConnectionCtx {
    /**socket连接*/
    SocketChannel channel
    /**用于携带额外参数*/
    Object attachment
    /**处理当前连接的工作线程*/
    Worker worker
    /**连接超时时间*/
    Long timeout
    /**每个连接拥有自己的pipeline*/
    PipeLine pipeLine
}
Copy after login

NioServer

主线程负责监听端口,持有工作线程的引用(使用轮转法分配连接),每次有连接到来时,将连接放入工作线程的连接队列,并唤醒线程selector.wakeup()(线程可能阻塞在selector上)。

class NioServer extends Thread {
    /**服务端的套接字通道*/
    ServerSocketChannel ssc
    /**选择器*/
    Selector selector
    /**事件总线*/
    PipeLine pipeLine
    /**工作线程列表*/
    def workers = []
    /**当前工作线程索引*/
    int index
}
Copy after login

Worker

工作线程,负责注册server传递过来的socket连接。主要监听读事件,管理socket,处理写操作。

class Worker extends Thread {
    /**选择器*/
    Selector selector
    /**读缓冲区*/
    ByteBuffer buffer
    /**主线程分配的连接队列*/
    def queue = []
    /**存储按超时时间从小到大的连接*/
    TreeMap<Long, ConnectionCtx> ctxTreeMap

    void run() {
        while (true) {
            selector.select()
            //注册主线程发送过来的连接
            registerCtx()
            //关闭超时的连接
            closeTimeoutCtx()
            //处理事件
            dispatchEvent()
        }
    }
}
Copy after login

运行一个简单的 Web 服务器

我实现了一系列处理HTTP请求的处理器,具体实现看代码。

  • LineBasedDecoder:行解码器,按行解析数据

  • HttpRequestDecoder:HTTP请求解析,目前只支持GET请求

  • HttpRequestHandler:Http 请求处理器,目前只支持GET方法

  • HttpResponseHandler:Http响应处理器

下面是写在test中的例子

class WebServerTest {
    static void main(args) {
        def pipeLine = new PipeLine()

        def readChain = new HandlerChain()
        readChain.addLast(new LineBasedDecoder())
        readChain.addLast(new HttpRequestDecoder())
        readChain.addLast(new HttpRequestHandler())
        readChain.addLast(new HttpResponseHandler())

        def closeChain = new HandlerChain()
        closeChain.addLast(new ClosedHandler())

        pipeLine.addChain(readChain)
        pipeLine.addChain(closeChain)

        NioServer nioServer = new NioServer(pipeLine)
        nioServer.start()
    }
}
Copy after login

另外,还可以使用配置文件getty.properties设置程序的运行参数。

#用于拼接消息时使用的二进制数组的缓存区
common_buffer_size=1024
#工作线程读取tcp数据的缓存大小
worker_rcv_buffer_size=1024
#监听的端口
port=4399
#工作线程的数量
worker_num=1
#连接超时自动断开时间
timeout=900
#根目录
root=.
Copy after login

总结

Getty是我造的第二个小轮子,第一个是RedisHttpSession。都说不要重复造轮子。这话我是认同的,但是掌握一门技术最好的方法就是实践,在没有合适项目可以使用新技术的时候,造一个简单的轮子是不错的实践手段。

Getty 的缺点或者说还可以优化的点:

  1. 线程的使用直接用了Thread类,看起来有点low。等以后水平提升了再来抽象一下。

  2. 目前只有读事件是异步的,写事件是同步的。未来将写事件也改为异步的。

The above is the detailed content of Getty-Detailed explanation of implementing Java NIO framework design. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1676
14
PHP Tutorial
1278
29
C# Tutorial
1257
24
PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP vs. Python: Core Features and Functionality PHP vs. Python: Core Features and Functionality Apr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHP's Impact: Web Development and Beyond PHP's Impact: Web Development and Beyond Apr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP: The Foundation of Many Websites PHP: The Foundation of Many Websites Apr 13, 2025 am 12:07 AM

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

PHP vs. Python: Use Cases and Applications PHP vs. Python: Use Cases and Applications Apr 17, 2025 am 12:23 AM

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.

See all articles