netty(三):NIO——多线程优化

NIO多线程优化

  • 使用Boss线程来处理accepct事件
  • 使用Worker线程来处理读写事件,可以创建多个worker线程
java 复制代码
package com.review;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.concurrent.ConcurrentLinkedQueue;

@Slf4j
public class MultiServer {
    public static void main(String[] args) throws IOException {
        Thread.currentThread().setName("BOSS");
        Selector selector = Selector.open();
        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.configureBlocking(false);
        ssc.bind(new InetSocketAddress(11027));
        SelectionKey sscKey = ssc.register(selector, 0, null);
        sscKey.interestOps(SelectionKey.OP_ACCEPT);
        Worker worker = new Worker("worker-0");
        while (true){
            selector.select();

            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            while (iterator.hasNext()){
                SelectionKey key = iterator.next();
                iterator.remove();

                if (key.isAcceptable()){
                    ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel();
                    SocketChannel sc = serverSocketChannel.accept();
                    sc.configureBlocking(false);
                    worker.register(sc);
                    worker.selector.wakeup();
                }
            }
        }

    }

    static class Worker implements Runnable{
        private String name;

        private Selector selector;

        private Thread thread;

        private volatile boolean start;

        ConcurrentLinkedQueue<Runnable> queue = new ConcurrentLinkedQueue<>();

        public Worker(String name){
            this.name = name;
        }

        public void register(SocketChannel sc) throws IOException {
            if (!start){
                selector = Selector.open();
                thread = new Thread(this,this.name);
                thread.start();
                start = true;
            }
            queue.add(()->{
                try {
                    SelectionKey scKey = sc.register(selector, 0, null);
                    scKey.interestOps(SelectionKey.OP_READ);
                } catch (ClosedChannelException e) {
                    log.error(e.getMessage(),e);
                }
            });
        }

        @Override
        public void run() {
            while (true){
                try {
                    selector.select();
                } catch (IOException e) {
                    log.error(e.getMessage(),e);
                }
                if (queue.size() > 0){
                    queue.poll().run();
                }
                Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                while (iterator.hasNext()){
                    SelectionKey selectionKey = iterator.next();
                    iterator.remove();

                    if (selectionKey.isReadable()){
                        SocketChannel channel = (SocketChannel) selectionKey.channel();
                    }

                }
            }
        }
    }
}

------------本专栏来自于对满叔在b站所讲的netty课程的理解

相关推荐
头顶秃成一缕光15 分钟前
若依——基于AI+若依框架的实战项目(实战篇(下))
java·前端·vue.js·elementui·aigc
白露与泡影43 分钟前
Java面试题及答案整理( 2025年 4 月最新版,持续更新)
java·开发语言
hunzi_11 小时前
选择网上购物系统要看几方面?
java·微信小程序·小程序·uni-app·php
ChinaRainbowSea1 小时前
1. 初始 RabbitMQ 消息队列
java·中间件·rabbitmq·java-rabbitmq
lmryBC491 小时前
golang接口-interface
java·前端·golang
ゞ 正在缓冲99%…1 小时前
leetcode75.颜色分类
java·数据结构·算法·排序
橘猫云计算机设计2 小时前
基于springboot的考研成绩查询系统(源码+lw+部署文档+讲解),源码可白嫖!
java·spring boot·后端·python·考研·django·毕业设计
时光呢2 小时前
JAVA常见的 JVM 参数及其典型默认值
java·开发语言·jvm
程序媛学姐2 小时前
SpringKafka错误处理:重试机制与死信队列
java·开发语言·spring·kafka
向阳2562 小时前
SpringBoot+vue前后端分离整合sa-token(无cookie登录态 & 详细的登录流程)
java·vue.js·spring boot·后端·sa-token·springboot·登录流程