当前位置:网站首页>NiO related knowledge (II)
NiO related knowledge (II)
2022-07-06 01:35:00 【Certainly tomorrow】
Looking back
NIO Relevant knowledge points ( One )_ If you have bad luck, try to make it up -CSDN Blog NIO?selector?epoll? I don't understand it https://blog.csdn.net/wai_58934/article/details/122898928?spm=1001.2014.3001.5501 Then continue to write yesterday .
The important thing is to call the three underlying functions , Namely
epoll_create: Generate a epoll Dedicated file descriptors . It actually applies for a space in the kernel , Used to store what you want to focus on socket fd Whether it happened and what happened
epoll_ctl:epoll The event registration function , Used to control a epoll Events on the file descriptor , You can register Events , Modify event , Delete event .
epoll_wait: Waiting for the event to happen , This function returns the number of events to be processed . Waiting to register at epfd Upper socket fd The occurrence of the event , If it happens, it will happen sokct fd And event types into events Array . And will register at epfd Upper socket fd The event type of , So if you want to focus on this in the next cycle socket fd Words , You need to use epoll_ctl To reset socket fd The type of event .
Reactor Respond to programming patterns
Reactor Encapsulates the selector.
Reactor The design pattern is event-driven architecture An implementation of , It is used to handle the scenario of multiple clients requesting services from the server concurrently . Each service may consist of multiple methods on the server .Reactor The service of concurrent requests will be decoupled and distributed to the corresponding time processor for processing .
Reactor The advantages of the model are obvious : decoupling 、 Improve reusability 、 modularization 、 Portability 、 Event driven 、 Fine grained development control, etc .Reactor The disadvantages of the model are also obvious : Complex model , Involving internal callback 、 Multithreading 、 Not easy to debug 、 The underlying support of the operating system is required , Therefore, different operating systems may produce different results .

yesterday NIO( Please review the above article link ) Although used selector, however disadvantages Still very big , Because it processes read and write events serially , If 100000 read / write events are being processed , Enter another connection , You need to wait for the previous event to be processed , Poor performance . Optimize : Put the read event into the thread pool for processing ( Establish connection events faster , There is no need to put it into the thread pool ). however , After adding the thread pool, it still Not in time Handle new requests ( Threads cannot be opened too much , It will cause memory overflow ). At this time, an excellent idea was born , Master-slave reactor The responsive model . One reactor Used to establish a connection , One reactor Deal with reading events .netty On this basis, improvements have been made , One master, many followers , Distribute events , In this way, the efficiency will be improved a lot . The above descriptions are : Single thread Reactor Model 、 Multithreading Reactor Model 、 Master-slave Reactor Model . You can compare the difference from the figure :



Take a look at netty To get started demo. Learn more about logic from the code .
The main thing is Create a startup object 、 Set the startup object 、 Binding port The three steps .
public static void main(String[] args) {
//boosGroup Only handle connection requests , The real business request is made by workGroup Handle
// In essence, it is to create n individual selector To deal with , Corresponding to the master-slave mentioned above
NioEventLoopGroup boosGroup = new NioEventLoopGroup(1);
NioEventLoopGroup workGroup = new NioEventLoopGroup(8);
try {
// Create a server-side startup object
ServerBootstrap bootstrap = new ServerBootstrap();
// Chain programming configures the startup object
bootstrap.group(boosGroup,workGroup)
.channel(NioServerSocketChannel.class) // Set the channel to achieve
.option(ChannelOption.SO_BACKLOG,1024) // Initialize server connection queue size , Put those that cannot be processed into the queue
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
socketChannel.pipeline().addLast(new NettyServerHandler());// Set up the processor , Focus on processing logic
}
});
System.out.println("netty server start");
// Binding port ,bind Is asynchronous ,sync To ensure the completion of asynchronous execution
ChannelFuture sync = bootstrap.bind(9000).sync();
// ditto , close future
sync.channel().closeFuture().sync();
} catch (Exception e) {
e.printStackTrace();
}finally {
boosGroup.shutdownGracefully();
workGroup.shutdownGracefully();
}
}Event implementation , Inherit ChannelInboundHandlerAdapter Rewrite the business you want to achieve .
public class NettyServerHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
System.out.println(" Successful connection ");
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
ByteBuf result = (ByteBuf) msg;
byte[] bytesMsg = new byte[result.readableBytes()];
result.readBytes(bytesMsg);
String resultStr = new String(bytesMsg);
System.out.println(" The data is :"+resultStr);
result.release();
}
}边栏推荐
- A picture to understand! Why did the school teach you coding but still not
- [flask] official tutorial -part1: project layout, application settings, definition and database access
- Leetcode 208. Implement trie (prefix tree)
- 插卡4G工业路由器充电桩智能柜专网视频监控4G转以太网转WiFi有线网速测试 软硬件定制
- Recommended areas - ways to explore users' future interests
- Code Review关注点
- 037 PHP login, registration, message, personal Center Design
- MySQL learning notes 2
- ORA-00030
- leetcode刷题_反转字符串中的元音字母
猜你喜欢

Alibaba-Canal使用详解(排坑版)_MySQL与ES数据同步

3D model format summary

c#网页打开winform exe

File upload vulnerability test based on DVWA

【Flask】官方教程(Tutorial)-part3:blog蓝图、项目可安装化

About error 2003 (HY000): can't connect to MySQL server on 'localhost' (10061)

【SSRF-01】服务器端请求伪造漏洞原理及利用实例
![[understanding of opportunity-39]: Guiguzi - Chapter 5 flying clamp - warning 2: there are six types of praise. Be careful to enjoy praise as fish enjoy bait.](/img/3c/ec97abfabecb3f0c821beb6cfe2983.jpg)
[understanding of opportunity-39]: Guiguzi - Chapter 5 flying clamp - warning 2: there are six types of praise. Be careful to enjoy praise as fish enjoy bait.

Basic operations of databases and tables ----- primary key constraints

Mongodb problem set
随机推荐
Alibaba-Canal使用详解(排坑版)_MySQL与ES数据同步
Force buckle 9 palindromes
[solved] how to generate a beautiful static document description page
VMware Tools installation error: unable to automatically install vsock driver
一圖看懂!為什麼學校教了你Coding但還是不會的原因...
National intangible cultural heritage inheritor HD Wang's shadow digital collection of "Four Beauties" made an amazing debut!
leetcode刷题_平方数之和
正则表达式:示例(1)
A Cooperative Approach to Particle Swarm Optimization
Redis-Key的操作
[技术发展-28]:信息通信网大全、新的技术形态、信息通信行业高质量发展概览
【Flask】获取请求信息、重定向、错误处理
ctf. Show PHP feature (89~110)
Tcpdump: monitor network traffic
国家级非遗传承人高清旺《四大美人》皮影数字藏品惊艳亮相!
基於DVWA的文件上傳漏洞測試
[the most complete in the whole network] |mysql explain full interpretation
【Flask】官方教程(Tutorial)-part2:蓝图-视图、模板、静态文件
一图看懂!为什么学校教了你Coding但还是不会的原因...
02.Go语言开发环境配置