it编程 > 游戏开发 > ar

深入理解tomcat中的BIO、NIO、AIO、ARP

24人参与 2025-04-16 ar

tomcat作为springboot中默认的web容器,了解tomcat的运转可以帮助我们更好的去调整tomcat的参数达到更好的性能

1. 前置知识

2. scoket测试工具

启动程序是jar包,必须要有jre环境
链接:https://sockettest.sourceforge.net

3. bio 同步阻塞io

每一个socket连接后,tomcat都会有一个线程去全程去陪伴,把请求转发到具体的容器中后,这个线程还在阻塞,等待容器返回数据,只有socket连接断开了,才会回收这个线程。tomcat7或以下默认,比较简单、稳定,适合连接数比较少的

模拟代码如下:

public class bioserver {
    static executorservice executorservice = executors.newcachedthreadpool();
    public static void main(string[] args) {
        try {
            // 启动服务,绑定8080端口
            serversocket serversocket = new serversocket();
            serversocket.bind(new inetsocketaddress(8080));
            system.out.println("开启服务");
            while (true){
                system.out.println("等待客户端建立连接");
                // 监听8080端口,获取客户端连接
                socket socket = serversocket.accept(); //阻塞
                system.out.println("建立连接:"+socket);
                executorservice.submit(()->{
                    //业务处理
                    try {
                        handler(socket);
                    } catch (ioexception e) {
                        e.printstacktrace();
                    }
                });
            }
        } catch (ioexception e) {
            e.printstacktrace();
        } finally {
            //todo 资源回收
        }
    }
    private static void handler(socket socket) throws ioexception {
        byte[] bytes = new byte[1024];
        system.out.println("等待读取数据");
        int read = socket.getinputstream().read(bytes); // 阻塞
        if(read !=-1) {
            system.out.println("读取客户端发送的数据:" +
                    new string(bytes, 0, read));
        }
    }
}

4. nio 同步非阻塞

一个socket连接过来,会经历以下步骤

tomcat8及以上默认, springboot2.3.12.release内嵌tomcat是9.0.46版本默认也是这个
模拟代码:

public class nioserver {
    public static void main(string[] args)  {
        list<socketchannel> list = new arraylist<>();  // 缓存所有的socket
        bytebuffer bytebuffer = bytebuffer.allocate(1024); // 缓存区的大小
        try {
            serversocketchannel serversocketchannel = serversocketchannel.open();
            // 监听8080
            serversocketchannel.bind(new inetsocketaddress(8080));
            // channel非阻塞
            serversocketchannel.configureblocking(false);
            system.out.println("nioserver 启动....");
            while (true){
                // 非阻塞
                socketchannel socketchannel = serversocketchannel.accept();
                thread.sleep(1000);
                if(socketchannel == null){
                    system.out.println("没有新的客户端建立连接");
                }else {
                    system.out.println("新的客户端建立连接");
                    // channel非阻塞
                    socketchannel.configureblocking(false);
                    // 将新的socket添加到 list
                    list.add(socketchannel);
                }
                //遍历所有的socket
                for(socketchannel channel:list){
                    //非阻塞
                    int read = channel.read(bytebuffer);
                    if(read >0) {
                        //读模式
                        bytebuffer.flip();
                        system.out.println("读取客户端发送的数据:" +new string(bytebuffer.array(),0,read));
                        bytebuffer.clear();
                    }
                }
            }
        } catch (exception e) {
            e.printstacktrace();
        }
    }
}

5. aio异步非阻塞

nio 和 aio(nio2) 最大的区别是,一个是同步一个是异步。异步最大的特点是,应用程序不需要自己去触发数据从内核空间到用户空间的拷贝。


没有 poller 组件,也就是没有 selector。在异步 i/o 模式下,selector 的工作交给
内核来做了。

linux 内核没有很完善地支持异步 i/o 模型,因此 jvm 并没有采用原生的 linux 异步 i/o,而是在应用层面通过 epoll 模拟了异步 i/o 模型。因此在 linux 平台上,java nio 和 java nio2 底层都是通过 epoll 来实现的,但是 java nio 更加简单高效。如果你的 tomcat 跑在 linux 平台上,建议不使用nio2

模拟代码:

public class aioserver {
    public asynchronousserversocketchannel serversocketchannel;
    public static void main(string[] args) throws exception {
        new aioserver().listen();
        thread.sleep(integer.max_value);
    }
    private void listen() throws ioexception {
        //1. 创建一个线程池
        executorservice es = executors.newcachedthreadpool();
        //2. 创建异步通道群组
        asynchronouschannelgroup acg = asynchronouschannelgroup.withcachedthreadpool(es, 1);
        //3. 创建服务端异步通道
        serversocketchannel = asynchronousserversocketchannel.open(acg);
        //4. 绑定监听端口
        serversocketchannel.bind(new inetsocketaddress(8080));
        system.out.println("aioserver 启动....");
        //5. 监听连接,传入回调类处理连接请求
        serversocketchannel.accept(this, new completionhandler<asynchronoussocketchannel, aioserver>() {
            //
            //            //具体处理连接请求的就是completed方法,它有两个参数:第一个是异步通道,第二个就是上面传入的aioserver对象
            @override
            public void completed(asynchronoussocketchannel socketchannel, aioserver attachment) {
                try {
                    if (socketchannel.isopen()) {
                        system.out.println("接收到新的客户端的连接,地址:"
                                + socketchannel.getremoteaddress());
                        final bytebuffer bytebuffer = bytebuffer.allocate(1024);
                        //调用 read 函数读取客户端发送的数据
                        socketchannel.read(bytebuffer, socketchannel,
                                        new completionhandler<integer, asynchronoussocketchannel>() {
                                            @override
                            public void completed(integer result, asynchronoussocketchannel attachment) {
                                try {
                                    //读取请求,处理客户端发送的数据
                                    bytebuffer.flip();
                                    string content = charset.defaultcharset()
                                            .newdecoder().decode(bytebuffer).tostring();
                                    system.out.println("服务端接受到客户端发来的数据:" + content);
                                } catch (charactercodingexception e) {
                                    e.printstacktrace();
                                }
                            }
                            @override
                            public void failed(throwable exc, asynchronoussocketchannel attachment) {
                                exc.printstacktrace();
                                try {
                                    attachment.close();
                                } catch (ioexception e) {
                                    e.printstacktrace();
                                }
                            }
                        });
                    }
                } catch (ioexception e) {
                    e.printstacktrace();
                }finally {
                    //当有新的客户端接入的时候,直接调用accept的方法
                    attachment.serversocketchannel.accept(attachment, this);
                }
            }
            @override
            public void failed(throwable exc, aioserver attachment) {
                exc.printstacktrace();
            }
        });
    }
}

6. apr异步非阻塞

apr方式全名叫apache portable runtime,需要额外去下载安装配置,nio2是调用java库去实现异步的,而arp是直接通过jni (java native interface)去操作系统是实现异步,apr 能够使用高级 io 功能 (如sendfile, epoll, openssl),sendfile主要是对静态文件提升很大,换apr也主要是这个原因其他的提升也不是特别大

附上对比图

springboot配置apr教程:https://www.jianshu.com/p/f716726ba340

到此这篇关于理解tomcat中的bio、nio、aio、arp的文章就介绍到这了,更多相关tomcat bio、nio、aio、arp内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)
打赏 微信扫一扫 微信扫一扫

您想发表意见!!点此发布评论

推荐阅读

ElasticSearch自定义注解增删改方式

04-17

HarmonyOS系统利用AVPlayer开发视频播放功能

04-20

Chrome拓展(Chrome Extension)开发定时任务插件

04-20

鸿蒙中@State的原理使用详解(HarmonyOS 5)

04-12

Pulsar简介及集群安装过程

04-25

Kotlin 作用域函数apply、let、run、with、also使用指南

04-03

猜你喜欢

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论