折腾了我一周,原来Netty网络编程就是这么个破玩意儿!!!

news2024/10/6 16:31:58

1、阻塞

  • 阻塞模式下,相关方法都会导致线程暂停
    • ServerSocketChannel.accept 会在没有连接建立时让线程暂停
    • SocketChannel.read 会在通道中没有数据可读时让线程暂停
    • 阻塞的表现其实就是线程暂停了,暂停期间不会占用 cpu,但线程相当于闲置
  • 单线程下,阻塞方法之间相互影响,几乎不能正常工作,需要多线程支持
  • 但多线程下,有新的问题,体现在以下方面
    • 32 位 jvm 一个线程 320k,64 位 jvm 一个线程 1024k,如果连接数过多,必然导致 OOM,并且线程太多,反而会因为频繁上下文切换导致性能降低
    • 可以采用线程池技术来减少线程数和线程上下文切换,但治标不治本,如果有很多连接建立,但长时间 inactive,会阻塞线程池中所有线程,因此不适合长连接,只适合短连接

服务端代码

public class Server {
    public static void main(String[] args) {
        // 创建缓冲区
        ByteBuffer buffer = ByteBuffer.allocate(16);
        // 获得服务器通道
        try(ServerSocketChannel server = ServerSocketChannel.open()) {
            // 为服务器通道绑定端口
            server.bind(new InetSocketAddress(8080));
            // 用户存放连接的集合
            ArrayList<SocketChannel> channels = new ArrayList<>();
            // 循环接收连接
            while (true) {
                System.out.println("before connecting...");
                // 没有连接时,会阻塞线程
                SocketChannel socketChannel = server.accept();
                System.out.println("after connecting...");
                channels.add(socketChannel);
                // 循环遍历集合中的连接
                for(SocketChannel channel : channels) {
                    System.out.println("before reading");
                    // 处理通道中的数据
                    // 当通道中没有数据可读时,会阻塞线程
                    channel.read(buffer);
                    buffer.flip();
                    ByteBufferUtil.debugRead(buffer);
                    buffer.clear();
                    System.out.println("after reading");
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

客户端代码

public class Client {
    public static void main(String[] args) {
        try (SocketChannel socketChannel = SocketChannel.open()) {
            // 建立连接
            socketChannel.connect(new InetSocketAddress("localhost", 8080));
            System.out.println("waiting...");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

运行结果

  • 客户端 - 服务器建立连接前:服务器端因 accept 阻塞

file

  • 客户端 - 服务器建立连接后,客户端发送消息前:服务器端因通道为空被阻塞

file

  • 客户端发送数据后,服务器处理通道中的数据。再次进入循环时,再次被 accept 阻塞

file

  • 之前的客户端再次发送消息,服务器端因为被 accept 阻塞,无法处理之前客户端发送到通道中的信息

file

2、非阻塞

  • 可以通过 ServerSocketChannel 的 configureBlocking (false) 方法将 获得连接设置为非阻塞的。此时若没有连接,accept 会返回 null
  • 可以通过 SocketChannel 的 configureBlocking (false) 方法将从通道中 读取数据设置为非阻塞的。若此时通道中没有数据可读,read 会返回 - 1

服务器代码如下

public class Server {
    public static void main(String[] args) {
        // 创建缓冲区
        ByteBuffer buffer = ByteBuffer.allocate(16);
        // 获得服务器通道
        try(ServerSocketChannel server = ServerSocketChannel.open()) {
            // 设置为非阻塞模式,没有连接时返回null,不会阻塞线程
            server.configureBlocking(false);
            // 为服务器通道绑定端口
            server.bind(new InetSocketAddress(8080));
            // 用户存放连接的集合
            ArrayList<SocketChannel> channels = new ArrayList<>();
            // 循环接收连接
            while (true) {
                
              
                SocketChannel socketChannel = server.accept();
                // 通道不为空时才将连接放入到集合中
                if (socketChannel != null) {
                    System.out.println("after connecting...");
                    channels.add(socketChannel);
                }
                // 循环遍历集合中的连接
                for(SocketChannel channel : channels) {
                    // 处理通道中的数据
                    // 设置为非阻塞模式,若通道中没有数据,会返回0,不会阻塞线程
                    channel.configureBlocking(false);
                    int read = channel.read(buffer);
                    if(read > 0) {
                        buffer.flip();
                        ByteBufferUtil.debugRead(buffer);
                        buffer.clear();
                        System.out.println("after reading");
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

这样写存在一个问题,因为设置为了非阻塞,会一直执行 while (true) 中的代码,CPU 一直处于忙碌状态,会使得性能变低,所以实际情况中不使用这种方法处理请求

3、Selector

多路复用

单线程可以配合 Selector 完成对多个 Channel 可读写事件的监控,这称之为多路复用

  • 多路复用仅针对网络 IO,普通文件 IO 无法利用多路复用
  • 如果不用 Selector 的非阻塞模式,线程大部分时间都在做无用功,而 Selector 能够保证
    • 有可连接事件时才去连接
    • 有可读事件才去读取
    • 有可写事件才去写入
      • 限于网络传输能力,Channel 未必时时可写,一旦 Channel 可写,会触发 Selector 的可写事件

4、使用及 Accpet 事件

要使用 Selector 实现多路复用,服务端代码如下改进

public class SelectServer {
    public static void main(String[] args) {
        ByteBuffer buffer = ByteBuffer.allocate(16);
        // 获得服务器通道
        try(ServerSocketChannel server = ServerSocketChannel.open()) {
            server.bind(new InetSocketAddress(8080));
            // 创建选择器
            Selector selector = Selector.open();
            
            // 通道必须设置为非阻塞模式
            server.configureBlocking(false);
            // 将通道注册到选择器中,并设置感兴趣的事件
            server.register(selector, SelectionKey.OP_ACCEPT);
            while (true) {
                // 若没有事件就绪,线程会被阻塞,反之不会被阻塞。从而避免了CPU空转
                // 返回值为就绪的事件个数
                int ready = selector.select();
                System.out.println("selector ready counts : " + ready);
                
                // 获取所有事件
                Set<SelectionKey> selectionKeys = selector.selectedKeys();
                
                // 使用迭代器遍历事件
                Iterator<SelectionKey> iterator = selectionKeys.iterator();
                while (iterator.hasNext()) {
                    SelectionKey key = iterator.next();
                    
                    // 判断key的类型
                    if(key.isAcceptable()) {
                        // 获得key对应的channel
                        ServerSocketChannel channel = (ServerSocketChannel) key.channel();
                        System.out.println("before accepting...");
                        
        				// 获取连接并处理,而且是必须处理,否则需要取消
                        SocketChannel socketChannel = channel.accept();
                        System.out.println("after accepting...");
                        
                        // 处理完毕后移除
                        iterator.remove();
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

步骤解析

  • 获得选择器 Selector
Selector selector = Selector.open();
  • 将通道设置为非阻塞模式,并注册到选择器中,并设置感兴趣的事件
    • channel 必须工作在非阻塞模式
    • FileChannel 没有非阻塞模式,因此不能配合 selector 一起使用
    • 绑定的事件类型可以有
      • connect - 客户端连接成功时触发
  • accept - 服务器端成功接受连接时触发
    • read - 数据可读入时触发,有因为接收能力弱,数据暂不能读入的情况
  • write - 数据可写出时触发,有因为发送能力弱,数据暂不能写出的情况
// 通道必须设置为非阻塞模式
server.configureBlocking(false);
// 将通道注册到选择器中,并设置感兴趣的实践
server.register(selector, SelectionKey.OP_ACCEPT);
  • 通过 Selector 监听事件,并获得就绪的通道个数,若没有通道就绪,线程会被阻塞

    • 阻塞直到绑定事件发生

      int count = selector.select();
      
    • 阻塞直到绑定事件发生,或是超时(时间单位为 ms)

      int count = selector.select(long timeout);
      
    • 不会阻塞,也就是不管有没有事件,立刻返回,自己根据返回值检查是否有事件

      int count = selector.selectNow();
      
  • 获取就绪事件并得到对应的通道,然后进行处理

// 获取所有事件
Set<SelectionKey> selectionKeys = selector.selectedKeys();
                
// 使用迭代器遍历事件
Iterator<SelectionKey> iterator = selectionKeys.iterator();

while (iterator.hasNext()) {
	SelectionKey key = iterator.next();
                    
	// 判断key的类型,此处为Accept类型
	if(key.isAcceptable()) {
        // 获得key对应的channel
        ServerSocketChannel channel = (ServerSocketChannel) key.channel();

        // 获取连接并处理,而且是必须处理,否则需要取消
        SocketChannel socketChannel = channel.accept();

        // 处理完毕后移除
        iterator.remove();
	}
}

事件发生后能否不处理

事件发生后,要么处理,要么取消(cancel),不能什么都不做,否则下次该事件仍会触发,这是因为 nio 底层使用的是水平触发

5、Read 事件

  • 在 Accept 事件中,若有客户端与服务器端建立了连接,需要将其对应的 SocketChannel 设置为非阻塞,并注册到选择其中
    添加 Read 事件,触发后进行读取操作
  • 添加 Read 事件,触发后进行读取操作
public class SelectServer {
    public static void main(String[] args) {
        ByteBuffer buffer = ByteBuffer.allocate(16);
        // 获得服务器通道
        try(ServerSocketChannel server = ServerSocketChannel.open()) {
            server.bind(new InetSocketAddress(8080));
            // 创建选择器
            Selector selector = Selector.open();
            // 通道必须设置为非阻塞模式
            server.configureBlocking(false);
            // 将通道注册到选择器中,并设置感兴趣的实践
            server.register(selector, SelectionKey.OP_ACCEPT);
            // 为serverKey设置感兴趣的事件
            while (true) {
                // 若没有事件就绪,线程会被阻塞,反之不会被阻塞。从而避免了CPU空转
                // 返回值为就绪的事件个数
                int ready = selector.select();
                System.out.println("selector ready counts : " + ready);
                // 获取所有事件
                Set<SelectionKey> selectionKeys = selector.selectedKeys();
                // 使用迭代器遍历事件
                Iterator<SelectionKey> iterator = selectionKeys.iterator();
                while (iterator.hasNext()) {
                    SelectionKey key = iterator.next();
                    // 判断key的类型
                    if(key.isAcceptable()) {
                        // 获得key对应的channel
                        ServerSocketChannel channel = (ServerSocketChannel) key.channel();
                        System.out.println("before accepting...");
                        // 获取连接
                        SocketChannel socketChannel = channel.accept();
                        System.out.println("after accepting...");
                        // 设置为非阻塞模式,同时将连接的通道也注册到选择其中
                        socketChannel.configureBlocking(false);
                        socketChannel.register(selector, SelectionKey.OP_READ);
                        // 处理完毕后移除
                        iterator.remove();
                    } else if (key.isReadable()) {
                        SocketChannel channel = (SocketChannel) key.channel();
                        System.out.println("before reading...");
                        channel.read(buffer);
                        System.out.println("after reading...");
                        buffer.flip();
                        ByteBufferUtil.debugRead(buffer);
                        buffer.clear();
                        // 处理完毕后移除
                        iterator.remove();
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

删除事件

当处理完一个事件后,一定要调用迭代器的 remove 方法移除对应事件,否则会出现错误。原因如下

以我们上面的 Read 事件 的代码为例

  • 当调用了 server.register (selector, SelectionKey.OP_ACCEPT) 后,Selector 中维护了一个集合,用于存放 SelectionKey 以及其对应的通道

    // WindowsSelectorImpl 中的 SelectionKeyImpl数组
    private SelectionKeyImpl[] channelArray = new SelectionKeyImpl[8];
    
    public class SelectionKeyImpl extends AbstractSelectionKey {
        // Key对应的通道
        final SelChImpl channel;
        ...
    }
    

file

  • 选择器中的通道对应的事件发生后,selecionKey 会被放到另一个集合中,但是 selecionKey 不会自动移除,所以需要我们在处理完一个事件后,通过迭代器手动移除其中的 selecionKey。否则会导致已被处理过的事件再次被处理,就会引发错误

file

断开处理

当客户端与服务器之间的连接断开时,会给服务器端发送一个读事件,对异常断开和正常断开需要加以不同的方式进行处理

  • 正常断开

    • 正常断开时,服务器端的 channel.read (buffer) 方法的返回值为 - 1,所以当结束到返回值为 - 1 时,需要调用 key 的 cancel 方法取消此事件,并在取消后移除该事件

      int read = channel.read(buffer);
      // 断开连接时,客户端会向服务器发送一个写事件,此时read的返回值为-1
      if(read == -1) {
          // 取消该事件的处理
      	key.cancel();
          channel.close();
      } else {
          ...
      }
      // 取消或者处理,都需要移除key
      iterator.remove();
      
  • 异常断开

    • 异常断开时,会抛出 IOException 异常, 在 try-catch 的 catch 块中捕获异常并调用 key 的 cancel 方法即可

消息边界

不处理消息边界存在的问题

将缓冲区的大小设置为 4 个字节,发送 2 个汉字(你好),通过 decode 解码并打印时,会出现乱码

ByteBuffer buffer = ByteBuffer.allocate(4);
// 解码并打印
System.out.println(StandardCharsets.UTF_8.decode(buffer));
你�
��

这是因为 UTF-8 字符集下,1 个汉字占用 3 个字节,此时缓冲区大小为 4 个字节,一次读时间无法处理完通道中的所有数据,所以一共会触发两次读事件。这就导致 你好 的 好 字被拆分为了前半部分和后半部分发送,解码时就会出现问题

处理消息边界

传输的文本可能有以下三种情况

  • 文本大于缓冲区大小
    • 此时需要将缓冲区进行扩容
  • 发生半包现象
  • 发生粘包现象

file

解决思路大致有以下三种

  • 固定消息长度,数据包大小一样,服务器按预定长度读取,当发送的数据较少时,需要将数据进行填充,直到长度与消息规定长度一致。缺点是浪费带宽

  • 另一种思路是按分隔符拆分,缺点是效率低,需要一个一个字符地去匹配分隔符

  • TLV 格式,即 Type 类型、Length 长度、Value 数据

    (也就是在消息开头用一些空间存放后面数据的长度),如 HTTP 请求头中的 Content-Type 与 Content-Length

    。类型和长度已知的情况下,就可以方便获取消息大小,分配合适的 buffer,缺点是 buffer 需要提前分配,如果内容过大,则影响 server 吞吐量

    • Http 1.1 是 TLV 格式
  • Http 2.0 是 LTV 格式

file

下文的消息边界处理方式为第二种:按分隔符拆分

附件与扩容

Channel 的 register 方法还有第三个参数:附件,可以向其中放入一个 Object 类型的对象,该对象会与登记的 Channel 以及其对应的 SelectionKey 绑定,可以从 SelectionKey 获取到对应通道的附件

public final SelectionKey register(Selector sel, int ops, Object att)

可通过 SelectionKey 的 attachment () 方法获得附件

ByteBuffer buffer = (ByteBuffer) key.attachment();

我们需要在 Accept 事件发生后,将通道注册到 Selector 中时,对每个通道添加一个 ByteBuffer 附件,让每个通道发生读事件时都使用自己的通道,避免与其他通道发生冲突而导致问题

// 设置为非阻塞模式,同时将连接的通道也注册到选择其中,同时设置附件
socketChannel.configureBlocking(false);
ByteBuffer buffer = ByteBuffer.allocate(16);
// 添加通道对应的Buffer附件
socketChannel.register(selector, SelectionKey.OP_READ, buffer);

当 Channel 中的数据大于缓冲区时,需要对缓冲区进行扩容操作。此代码中的扩容的判定方法: Channel 调用 compact 方法后,的 position 与 limit 相等,说明缓冲区中的数据并未被读取(容量太小),此时创建新的缓冲区,其大小扩大为两倍。同时还要将旧缓冲区中的数据拷贝到新的缓冲区中,同时调用 SelectionKey 的 attach 方法将新的缓冲区作为新的附件放入 SelectionKey 中

// 如果缓冲区太小,就进行扩容
if (buffer.position() == buffer.limit()) {
    ByteBuffer newBuffer = ByteBuffer.allocate(buffer.capacity()*2);
    // 将旧buffer中的内容放入新的buffer中
    ewBuffer.put(buffer);
    // 将新buffer作为附件放到key中
    key.attach(newBuffer);
}

改造后的服务器代码如下

public class SelectServer {
    public static void main(String[] args) {
        // 获得服务器通道
        try(ServerSocketChannel server = ServerSocketChannel.open()) {
            server.bind(new InetSocketAddress(8080));
            // 创建选择器
            Selector selector = Selector.open();
            // 通道必须设置为非阻塞模式
            server.configureBlocking(false);
            // 将通道注册到选择器中,并设置感兴趣的事件
            server.register(selector, SelectionKey.OP_ACCEPT);
            // 为serverKey设置感兴趣的事件
            while (true) {
                // 若没有事件就绪,线程会被阻塞,反之不会被阻塞。从而避免了CPU空转
                // 返回值为就绪的事件个数
                int ready = selector.select();
                System.out.println("selector ready counts : " + ready);
                // 获取所有事件
                Set<SelectionKey> selectionKeys = selector.selectedKeys();
                // 使用迭代器遍历事件
                Iterator<SelectionKey> iterator = selectionKeys.iterator();
                
                while (iterator.hasNext()) {
                    SelectionKey key = iterator.next();
                    iterator.remove();
                    // 判断key的类型
                    if(key.isAcceptable()) {
                        // 获得key对应的channel
                        ServerSocketChannel channel = (ServerSocketChannel) key.channel();
                        System.out.println("before accepting...");
                        // 获取连接
                        SocketChannel socketChannel = channel.accept();
                        System.out.println("after accepting...");
                        // 设置为非阻塞模式,同时将连接的通道也注册到选择其中,同时设置附件
                        socketChannel.configureBlocking(false);
                        ByteBuffer buffer = ByteBuffer.allocate(16);
                        socketChannel.register(selector, SelectionKey.OP_READ, buffer);
                        
                        
                    } else if (key.isReadable()) {
                        SocketChannel channel = (SocketChannel) key.channel();
                        System.out.println("before reading...");
                        // 通过key获得附件(buffer)
                        ByteBuffer buffer = (ByteBuffer) key.attachment();
                        int read = channel.read(buffer);
                        if(read == -1) {
                            key.cancel();
                            channel.close();
                        } else {
                            // 通过分隔符来分隔buffer中的数据
                            split(buffer);
                            // 如果缓冲区太小,就进行扩容
                            if (buffer.position() == buffer.limit()) {
                                ByteBuffer newBuffer = ByteBuffer.allocate(buffer.capacity()*2);
                                // 将旧buffer中的内容放入新的buffer中
                                buffer.flip();
                                newBuffer.put(buffer);
                                // 将新buffer放到key中作为附件
                                key.attach(newBuffer);
                            }
                        }
                        System.out.println("after reading...");
                       
                       
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void split(ByteBuffer buffer) {
        buffer.flip();
        for(int i = 0; i < buffer.limit(); i++) {
            // 遍历寻找分隔符
            // get(i)不会移动position
            if (buffer.get(i) == '\n') {
                // 缓冲区长度
                int length = i+1-buffer.position();
                ByteBuffer target = ByteBuffer.allocate(length);
                // 将前面的内容写入target缓冲区
                for(int j = 0; j < length; j++) {
                    // 将buffer中的数据写入target中
                    target.put(buffer.get());
                }
                // 打印结果
                ByteBufferUtil.debugAll(target);
            }
        }
        // 切换为写模式,但是缓冲区可能未读完,这里需要使用compact
        buffer.compact();
    }
}

ByteBuffer 的大小分配

  • 每个 channel 都需要记录可能被切分的消息,因为 ByteBuffer 不能被多个 channel 共同使用,因此需要为每个 channel 维护一个独立的 ByteBuffer
  • ByteBuffer 不能太大,比如一个 ByteBuffer 1Mb 的话,要支持百万连接就要 1Tb 内存,因此需要设计大小可变的 ByteBuffer
  • 分配思路可以参考
    • 一种思路是首先分配一个较小的 buffer,例如 4k,如果发现数据不够,再分配 8k 的 buffer,将 4k buffer 内容拷贝至 8k buffer,优点是消息连续容易处理,缺点是数据拷贝耗费性能
    • 另一种思路是用多个数组组成 buffer,一个数组不够,把多出来的内容写入新的数组,与前面的区别是消息存储不连续解析复杂,优点是避免了拷贝引起的性能损耗

6、Write 事件

服务器通过 Buffer 向通道中写入数据时,可能因为通道容量小于 Buffer 中的数据大小,导致无法一次性将 Buffer 中的数据全部写入到 Channel 中,这时便需要分多次写入,具体步骤如下

  • 执行一次写操作,向将 buffer 中的内容写入到 SocketChannel 中,然后判断 Buffer 中是否还有数据

  • 若 Buffer 中还有数据,则需要将 SockerChannel 注册到 Seletor 中,并关注写事件,同时将未写完的 Buffer 作为附件一起放入到 SelectionKey 中

 int write = socket.write(buffer);
// 通道中可能无法放入缓冲区中的所有数据
if (buffer.hasRemaining()) {
    // 注册到Selector中,关注可写事件,并将buffer添加到key的附件中
    socket.configureBlocking(false);
    socket.register(selector, SelectionKey.OP_WRITE, buffer);
}
  • 添加写事件的相关操作 key.isWritable(),对 Buffer 再次进行写操作
    • 每次写后需要判断 Buffer 中是否还有数据(是否写完)。若写完,需要移除 SelecionKey 中的 Buffer 附件,避免其占用过多内存,同时还需移除对写事件的关注
SocketChannel socket = (SocketChannel) key.channel();
// 获得buffer
ByteBuffer buffer = (ByteBuffer) key.attachment();
// 执行写操作
int write = socket.write(buffer);
System.out.println(write);
// 如果已经完成了写操作,需要移除key中的附件,同时不再对写事件感兴趣
if (!buffer.hasRemaining()) {
    key.attach(null);
    key.interestOps(0);
}

整体代码如下

public class WriteServer {
    public static void main(String[] args) {
        try(ServerSocketChannel server = ServerSocketChannel.open()) {
            server.bind(new InetSocketAddress(8080));
            server.configureBlocking(false);
            Selector selector = Selector.open();
            server.register(selector, SelectionKey.OP_ACCEPT);
            while (true) {
                selector.select();
                Set<SelectionKey> selectionKeys = selector.selectedKeys();
                Iterator<SelectionKey> iterator = selectionKeys.iterator();
                while (iterator.hasNext()) {
                    SelectionKey key = iterator.next();
                    // 处理后就移除事件
                    iterator.remove();
                    if (key.isAcceptable()) {
                        // 获得客户端的通道
                        SocketChannel socket = server.accept();
                        // 写入数据
                        StringBuilder builder = new StringBuilder();
                        for(int i = 0; i < 500000000; i++) {
                            builder.append("a");
                        }
                        ByteBuffer buffer = StandardCharsets.UTF_8.encode(builder.toString());
                        // 先执行一次Buffer->Channel的写入,如果未写完,就添加一个可写事件
                        int write = socket.write(buffer);
                        System.out.println(write);
                        // 通道中可能无法放入缓冲区中的所有数据
                        if (buffer.hasRemaining()) {
                            // 注册到Selector中,关注可写事件,并将buffer添加到key的附件中
                            socket.configureBlocking(false);
                            socket.register(selector, SelectionKey.OP_WRITE, buffer);
                        }
                    } else if (key.isWritable()) {
                        SocketChannel socket = (SocketChannel) key.channel();
                        // 获得buffer
                        ByteBuffer buffer = (ByteBuffer) key.attachment();
                        // 执行写操作
                        int write = socket.write(buffer);
                        System.out.println(write);
                        // 如果已经完成了写操作,需要移除key中的附件,同时不再对写事件感兴趣
                        if (!buffer.hasRemaining()) {
                            key.attach(null);
                            key.interestOps(0);
                        }
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

7、优化

多线程优化

充分利用多核 CPU,分两组选择器

  • 单线程配一个选择器(Boss),专门处理 accept 事件
  • 创建 cpu 核心数的线程(Worker),每个线程配一个选择器,轮流处理 read 事件
实现思路
  • 创建一个负责处理 Accept 事件的 Boss 线程,与多个负责处理 Read 事件的 Worker 线程

  • Boss 线程执行的操作

    • 接受并处理 Accepet 事件,当 Accept 事件发生后,调用 Worker 的 register (SocketChannel socket) 方法,让 Worker 去处理 Read 事件,其中需要根据标识 robin 去判断将任务分配给哪个 Worker

      // 创建固定数量的Worker
      Worker[] workers = new Worker[4];
      // 用于负载均衡的原子整数
      AtomicInteger robin = new AtomicInteger(0);
      // 负载均衡,轮询分配Worker
      workers[robin.getAndIncrement()% workers.length].register(socket);
      
    • register (SocketChannel socket) 方法会通过同步队列完成 Boss 线程与 Worker 线程之间的通信,让 SocketChannel 的注册任务被 Worker 线程执行。添加任务后需要调用 selector.wakeup () 来唤醒被阻塞的 Selector

      public void register(final SocketChannel socket) throws IOException {
          // 只启动一次
          if (!started) {
             // 初始化操作
          }
          // 向同步队列中添加SocketChannel的注册事件
          // 在Worker线程中执行注册事件
          queue.add(new Runnable() {
              @Override
              public void run() {
                  try {
                      socket.register(selector, SelectionKey.OP_READ);
                  } catch (IOException e) {
                      e.printStackTrace();
                  }
              }
          });
          // 唤醒被阻塞的Selector
          // select类似LockSupport中的park,wakeup的原理类似LockSupport中的unpark
          selector.wakeup();
      }
      
  • Worker 线程执行的操作

    • 从同步队列中获取注册任务,并处理 Read 事件
实现代码
public class ThreadsServer {
    public static void main(String[] args) {
        try (ServerSocketChannel server = ServerSocketChannel.open()) {
            // 当前线程为Boss线程
            Thread.currentThread().setName("Boss");
            server.bind(new InetSocketAddress(8080));
            // 负责轮询Accept事件的Selector
            Selector boss = Selector.open();
            server.configureBlocking(false);
            server.register(boss, SelectionKey.OP_ACCEPT);
            // 创建固定数量的Worker
            Worker[] workers = new Worker[4];
            // 用于负载均衡的原子整数
            AtomicInteger robin = new AtomicInteger(0);
            for(int i = 0; i < workers.length; i++) {
                workers[i] = new Worker("worker-"+i);
            }
            while (true) {
                boss.select();
                Set<SelectionKey> selectionKeys = boss.selectedKeys();
                Iterator<SelectionKey> iterator = selectionKeys.iterator();
                while (iterator.hasNext()) {
                    SelectionKey key = iterator.next();
                    iterator.remove();
                    // BossSelector负责Accept事件
                    if (key.isAcceptable()) {
                        // 建立连接
                        SocketChannel socket = server.accept();
                        System.out.println("connected... ");
                        socket.configureBlocking(false);
                        // socket注册到Worker的Selector中
                        System.out.println("before read...");
                        // 负载均衡,轮询分配Worker
                        workers[robin.getAndIncrement()% workers.length].register(socket);
                        System.out.println("after read...");
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    static class Worker implements Runnable {
        private Thread thread;
        private volatile Selector selector;
        private String name;
        private volatile boolean started = false;
        /**
         * 同步队列,用于Boss线程与Worker线程之间的通信
         */
        private ConcurrentLinkedQueue<Runnable> queue;

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

        public void register(final SocketChannel socket) throws IOException {
            // 只启动一次
            if (!started) {
                thread = new Thread(this, name);
                selector = Selector.open();
                queue = new ConcurrentLinkedQueue<>();
                thread.start();
                started = true;
            }
            
            // 向同步队列中添加SocketChannel的注册事件
            // 在Worker线程中执行注册事件
            queue.add(new Runnable() {
                @Override
                public void run() {
                    try {
                        socket.register(selector, SelectionKey.OP_READ);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            });
            // 唤醒被阻塞的Selector
            // select类似LockSupport中的park,wakeup的原理类似LockSupport中的unpark
            selector.wakeup();
        }

        @Override
        public void run() {
            while (true) {
                try {
                    selector.select();
                    // 通过同步队列获得任务并运行
                    Runnable task = queue.poll();
                    if (task != null) {
                        // 获得任务,执行注册操作
                        task.run();
                    }
                    Set<SelectionKey> selectionKeys = selector.selectedKeys();
                    Iterator<SelectionKey> iterator = selectionKeys.iterator();
                    while(iterator.hasNext()) {
                        SelectionKey key = iterator.next();
                        iterator.remove();
                        // Worker只负责Read事件
                        if (key.isReadable()) {
                            // 简化处理,省略细节
                            SocketChannel socket = (SocketChannel) key.channel();
                            ByteBuffer buffer = ByteBuffer.allocate(16);
                            socket.read(buffer);
                            buffer.flip();
                            ByteBufferUtil.debugAll(buffer);
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

本文由传智教育博学谷教研团队发布。

如果本文对您有帮助,欢迎关注点赞;如果您有任何建议也可留言评论私信,您的支持是我坚持创作的动力。

转载请注明出处!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/126652.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

flowable学习笔记(四):动态多实例

1.定义流程模板 【测试用户任务多实例】任务节点配置了以下属性&#xff1a; 集合(多实例)&#xff1a;userList。这个创建流程实例时入参需要加上这个参数。 元素变量(多实例)&#xff1a;user。工作流创建多实例时会将集合(多实例)的值拆分成元素变量(多实例)&#xff0c;这个…

Git复习,GitHub\Gitee的使用,IDEA集成Git

今天想把自己的课设上传到GitHub&#xff0c;因为长久不用&#xff0c;Git的命令忘得差不多了&#xff0c;所以今天把Git重新学一遍。 文章目录Git的介绍Git的安装Git的常用命令工作机制常用命令用户签名初始化本地库查看本地库状态添加暂存区提交本地库查看引用日志信息修改文…

Python常用函数笔记汇总2

1.分组汇总groupby 2.计算空值 # py计算空值 data.isnull().sum(axis0) data.notnull().sum(axis0)# py去重计数 data_op[id_num_op].value_counts().size data_op[id_num_op].size3.保留两位小数 # predict_proba保留两位小数 gnb GaussianNB() pre gnb.fit(X_train,y_tr…

pytest-日志配置

如果想要在run测试用例时&#xff0c;打印出由python的logging的日志&#xff0c;可以在pytest中进行相应的配置 pytest可以将日志输出到控制台或者文件中&#xff0c;分别对应不同的配置项 pytest的日志配置文件主要在pytest.ini文件中进行配置&#xff0c;包括配置日志的格式…

ARM64内存虚拟化分析(5)内存布局更新

1 添加MR 创建的MR需要通过函数memory_region_add_subregion()添加到系统中&#xff0c;提交MR&#xff0c;并最终往KVM提交内存的变化。 过程如下&#xff1a; 将mr设置为subregion的container&#xff1b;设置subregion在虚拟机中的物理地址&#xff1b;调用memory_region_t…

FOHEART H1数据手套_Unity3D SDK开发

本教程介绍使用FOHEART H1数据手套在Unity3D中&#xff0c;显示每段骨骼的位置与旋转信息。 需要准备的软硬件&#xff1a; 1、FOHEART H1数据手套 2、MotionVenus客户端 3、Unity3D软件 4、开发包MotionVenus_U3DPlugin_v2.0_H1GloveDev_SDKTest.unitypackage 1、连接数…

HFSS学习笔记

以下所有操作&#xff0c;都是基于2022版本的HFSS。一、HFSS solution模式选择位置&#xff1a;HFSS-Solution type类型表格。二、单位设置位置&#xff1a;Modeler-Units点击后&#xff0c;通常选用单位为&#xff1a;mm三、绘制物体点击红圈1的draw&#xff0c;右侧有些形状可…

MCU-51:单片机实时时钟

目录一、什么是时钟1.1 实时时钟1.2 时序二、DS1302实时时钟2.1 DS1302介绍2.2 引脚定义和应用电路三、代码演示3.1 数字时钟3.2 DS1302可调时钟注意&#xff1a;一定要看一、什么是时钟 1.1 实时时钟 real time clock&#xff0c;真实时间&#xff0c;就是所谓的xx年x月x日x…

我的统计学学习笔记(持续更新)

目录数据&#xff1a;变量和观测统计学描述统计数据的收集数据的可视化数据的规律性特征统计推断参数估计假设检验贝叶斯统计基础知识&#xff1a;概率论数据&#xff1a;变量和观测 变量(column)、观测(row)、测量(assign number to observation)。 统计学 描述统计 数据…

YOLO-V5 系列算法和代码解析(四)—— 网络结构

文章目录辅助工具网络配置文件网络构建网络推理绘制网络结构辅助工具 借助辅助工具可视化网络结构&#xff0c;达到辅助阅读代码&#xff0c;进而辅助手动绘制结构清晰的网络结构&#xff0c;最终理解整个网络架构的目的&#xff0c;为深入学习【yolo-v5】提供有效的保障。 ten…

阿里妈妈内容风控模型预估引擎的探索和建设

作者&#xff1a;徐雄飞、金禄旸、滑庆波、李治 内容作为营销的重要载体&#xff0c;能够促进信息的交流和传播。在营销场景中&#xff0c;广告高曝光的特性放大了风险外漏带来的一系列问题&#xff0c;因此对内容的风控审核就显得至关重要。本文将为大家分享阿里妈妈内容风控模…

DOM节点操作

节点操作 改变元素节点中的内容可以使用两个相关属性&#xff1a;innerHTML innerText 注意字符串不能换行 innerHTML属性能以HTML语法设置节点中的内容 innerText属性只能以纯文本的形式设置节点中的内容 节点创建 document.createElement()方法用于创建一个指定tagname…

android studio编译慢

前言 android studio编译慢一直就是一个问题&#xff0c;很久以前使用eclipse&#xff0c;编译速度很快&#xff0c;在还没开始正式工作的时候就开始使用android studio&#xff0c;那时候还是0.8 很原始&#xff0c;主要那时候还没开始工作&#xff0c;所以编译快慢没感觉&am…

TikTok Shop跨境服务市场上线;俄罗斯速卖通发布延误通知

让我们一起来看看今日都有哪些新鲜事吧&#xff01;01 TikTok Shop跨境服务市场上线 12月28日消息&#xff0c;服务商是助力商家在TikTok Shop成长非常重要的合作伙伴&#xff0c;TikTok Shop希望通过上线服务市场帮助商家快速了解服务商&#xff0c;筛选符合自身需求的服务商…

【JavaSE成神之路】Java面向对象(上)

哈喽&#xff0c;我是兔哥呀&#xff0c;今天就让我们继续这个JavaSE成神之路&#xff01; 这一节啊&#xff0c;咱们要学习的内容是Java的面向对象。 首先我们回顾一下&#xff0c;之前的章节我们学到了哪些东西。 我们学会了写一个类&#xff0c;然后里面弄一个main方法&am…

layer2 实现方式之状态通道

状态通道也算是一种比较热门的扩容方案&#xff0c;状态通道解决方案通过将链下交互和链上清算隔离开&#xff0c;能够在保障一定程度的非中心化和资产安全性的同时&#xff0c;实现速度更快、费用更低的交易。状态通道作为一种链下扩容方案&#xff0c;从一般到特殊分为通用状…

时光飞逝,博客两周年啦

原文链接&#xff1a;时光飞逝&#xff0c;博客两周年啦 博客自 2020年12月10日 运营以来&#xff0c;已经成功走过两年啦&#xff08;差点成为两年半的博主&#xff09;。 在这两年中&#xff0c;曾替无数网友解答了各种关于建站的疑难杂症&#xff0c;此处略过 30000 字。 …

linux系统动态库的连接

前言&#xff1a;在应用程序开发过程中&#xff0c;难免会用到第三方库&#xff0c;有的是开源的第三方库&#xff0c;有的是不开源的&#xff0c;还有的是自己写的库。上篇文章总结了应用程序调用静态库《linux中静态库编译与使用》&#xff0c;本文总结了几种在应用程序中快速…

八、esp8266建立基本网络服务器

1、网络服务器 (1)网络服务器有很多类型&#xff0c;它们功能十分丰富。通常承担网络服务器工作的设备都是运算能力比较强大的电脑。 (2)ESP8266虽然也能实现网络服务器的一些功能&#xff0c;但是毕竟它的运算能力是无法与那些昂贵的服务器电脑相比较&#xff0c;因此ESP826…

STM32的升级--ICP/ISP/IAP

ICP/ISP/IAP 区别 ICP(In-Circuit Programing): 通过J-Link/SWD等下载器烧写程序&#xff0c;上位机需要借助其他硬件的参与才能更新固件&#xff0c;可以更新MCU的所有存储区域&#xff1b; ISP(In-System Programing): 通过MCU出厂时固化的一个bootloader升级程序&#xff0…