java 伪异步 netty,大话netty系列之--伪异步BIO

生意规模扩大

话说,老王和大明的生意越来越好,这就需要两个人增强业务往来,由于天南地北,两个人只能每次运输都需要雇一个人去运货(new 一个线程),一个月下来,两人一算,人力成本太大了,光是雇佣人一个月就用了将近一百个人,本来生意旺盛,却还亏损了。两个人思来想去,想到了一个好主意,可以租个宿舍,就固定雇佣几个人,谁闲着谁就去运输,这样可以大大降低人的数量,又可以充分发挥人的效率。

其实上面这种思路就是服务端每次新连接客户端不在new一个线程,二是创建一个线程池,这样避免线程的大量创建,下面我们来用代码实现下以上的逻辑。

首先创建老王类,和昨天的BIO没有什么区别:

/**

* 伪异步请求 老王

*

* @author wangmj

* @since 2018/11/19

*/

public class FakeBioClient {

public static void main(String[] args) {

int port = 8761;

Socket socket = null;

PrintWriter out = null;

BufferedReader in = null;

try {

//创建客户端soket--老王

socket = new Socket("127.0.0.1", port);

while (true) {

//获取输出流,向服务器发送消息

OutputStream os = socket.getOutputStream();

out = new PrintWriter(os, true);

out.println("今天给你发送东北特产100斤,发送时间:" + new Date());

System.out.println("老王的东北特产成功送出");

in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

//收到服务端的响应

String resp = in.readLine();

System.out.println("收到大明的反馈=" + resp);

Thread.sleep(500);

}

} catch (IOException e) {

e.printStackTrace();

} catch (InterruptedException e) {

e.printStackTrace();

} finally {

if (out != null) {

out.close();

}

try {

if (in != null) {

in.close();

}

if (socket != null) {

socket.close();

}

} catch (IOException e) {

e.printStackTrace();

}

}

}

}

接着我们创建工人管理宿舍—线程池

/**

* @author wangmj

* @since 2018/11/19

*/

public class FakeBioServerExecutePool {

private ExecutorService executor;

public FakeBioServerExecutePool() {

executor = new ThreadPoolExecutor(Runtime.getRuntime().availableProcessors(), 100, 120L, TimeUnit.SECONDS, new ArrayBlockingQueue(5000));

}

public void execute(Runnable task) {

executor.execute(task);

}

}

有一点需要提醒,创建线程池不要用Excecutors类创建,尽量用new ThreadPoolExecutor创建,因为这样可以自己定义线程池参数,并且可以自己定义拒绝策略。

现在我们继续创建小美类,大明的具体业务处理对象:

/**

* @author wangmj

* @since 2018/11/19

*/

public class FakeBioServerHandler implements Runnable {

private Socket socket;

public FakeBioServerHandler(Socket socket) {

this.socket = socket;

}

public void run() {

BufferedReader in = null;

PrintWriter out = null;

try {

in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

out = new PrintWriter(socket.getOutputStream(), true);

//从大明收到的特产

String messageFromDM = null;

while (true) {

messageFromDM = in.readLine();

if (messageFromDM == null) {

break;

}

System.out.println("收到老王的特产=" + messageFromDM);

out.println("老铁,已收到特产,接收时间:" + new Date());

System.out.println("通知老王已收到特产");

}

} catch (IOException e) {

e.printStackTrace();

} finally {

try {

if (in != null) {

in.close();

}

} catch (IOException e) {

e.printStackTrace();

}

if (out != null) {

out.close();

}

}

}

}

最后我们创建大明类:

/**

* 大明类,负责接收老王发过来的特产

*

* @author wangmj

* @since 2018/11/19

*/

public class FakeBioServer {

public static void main(String[] args) {

int port = 8761;

Socket socket = null;

try {

//创建大明类

ServerSocket serverSocket = new ServerSocket(port);

socket = serverSocket.accept();

System.out.println("创建大明类成功,并阻塞等待老王发送的特产");

FakeBioServerExecutePool executePool = new FakeBioServerExecutePool();

executePool.execute(new FakeBioServerHandler(socket));

} catch (IOException e) {

e.printStackTrace();

}

}

}

好,这样一条龙我们就都创建完毕,包括了客户端,服务端及服务端的线程池,让我们运行下查看结果,

客户端运行结果—老王类

c5c8d6d5e623094e5ae60c1e94235e0d.png

服务端运行结果–大明类

62f8642e0823a355764b069b20484ff6.png

原理分析

首先,这次创建的客户端及服务端还是基于BIO,也就是说读写还是会同步阻塞,只不过这次我们将服务端每次接收新的连接不是每次都new Thread创建线程,而是用线程池来管理线程,想以此来减少线程的创建,并且设定了一个最大任务队列;模型图如下(模型图用的processon画的,画的不怎么好)

91dd919925fc2e8af88e6dd2bc5a1249.png

分析:

当任务足够多,并且网络较差,造成一次IO的时间过多,就会造成队列堆积大量等待任务,由于服务端只有一个acceptor处理,新的客户端连接就会被拒绝,那么最终会导致队列中堆积大量的请求,同时客户端连接失败,服务端CPU飙升,系统崩溃,所以伪异步IO模型解决不了问题

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

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

相关文章

如何使用Windows搜索在任何文件中搜索文本

Many of us rely on Windows Search to find files and launch programs, but searching for text within files is limited to specific file types by default. Here’s how you can expand your search to include other text-based files. 我们中的许多人都依赖Windows搜索…

php算法求出兔子数列,PHP算法:斐波那契数列的N种算法

前言前段时间,遇到优化计算斐波那契数列的常规递归方法,但是一时间并没有及时想到很好的方法,所以后面查找了相关资料,总结了多种计算解法,所以分享出来,和大家一起交流学习。斐波那契数是什么斐波那契数列…

.net core MongoDB 初试

是这样的&#xff0c;我们有一个场景&#xff0c;另一个服务器是写到MongoDB里面&#xff0c;我们的MVC页面要展示&#xff0c;需要分页展示 自己写了一个DAL public class MongoConnect{public string ConnectString { get; set; }}public class MongoBaseDAL<TEntity>{…

Linux文件和目录权限:chmod、更改所有者和所属组:chown,umask命令,隐藏权限:lsattr/chattr...

文件和目录权限chmod&#xff1a; 我们使用ls -l可以看到文件的详细信息&#xff0c;也知道第一列的第一个符号(字母)表示文件的类型&#xff0c;在表示文件的类型符号的后面的九个符号则表示的是文件的权限&#xff0c;这些权限和文件的所有者和所属组都有关系&#xff1a; 文…

【技术累积】【点】【java】【27】@JSONField

JSONField 该注解隶属于阿里fastjson&#xff0c;方便fastjson处理对象时的一些操作 源码 Retention(RetentionPolicy.RUNTIME) Target({ ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER }) public interface JSONField {/*** config encode/decode ordinal* s…

百度php editor图片上传到其他盘,百度编辑器Editor图片独立上传

将百度编辑器中的图片独立出来上传&#xff1a;html:代码var myEditorImage,d,myEditorImage new UE.ui.Editor();myEditorImage.render(uploadid);myEditorImage.ready(function(){myEditorImage.setDisabled();myEditorImage.hide();//隐藏UE框体myEditorImage.addListener(…

感谢支持,超预期重印并加码

今天&#xff0c;要向广大读者朋友带来一个&#xff0c;连我自己和出版社都感到十分意外的好消息&#xff0c;几天前接到出版社的通知&#xff0c;说今年元月出版的《Cisco/H3C交换机配置与管理完全手册》&#xff08;第二版&#xff09;马上就要下单重印了&#xff0c;而且一下…

如何从手机远程控制uTorrent

You’re a geek on the go and it’s important to keep tabs on your torrents when you’re away from home. Today we take a peak at how you can monitor, manage, and even start your torrent downloads when you’re away from your computer. 您是旅途中的怪胎&#x…

洛谷P2463 Sandy的卡片【后缀数组】【二分】

题目描述 Sandy和Sue的热衷于收集干脆面中的卡片。 然而&#xff0c;Sue收集卡片是因为卡片上漂亮的人物形象&#xff0c;而Sandy则是为了积攒卡片兑换超炫的人物模型。 每一张卡片都由一些数字进行标记&#xff0c;第i张卡片的序列长度为Mi&#xff0c;要想兑换人物模型&#…

php获取一个文件名的函数,PHP 文件系统函数之获取文件名及文件名后缀-php文件...

获取文件名(包含扩展):1.用PHP 文件函数 basename获取例&#xff1a;$filename "/home/httpd/html/index.php";$file basename($filename);2.先获取位置再获取文件名例:$filename "/home/httpd/html/index.php";$pos strrpos($filename, /);if ($pos …

tasker使用手册_如何开始使用Tasker调整Android手机

tasker使用手册Tasker is a powerful app for Android that lets you customize how your phone works and automate tasks. Unfortunately, it’s got a bit of a learning curve. We’re here to show you how to get started and turn your phone into a flashlight in the …

iPhone 软件:xlate free 编码的好帮手!

功能菜单&#xff1a; 1 文本 2 二进制 3 Char 值 4 Base64 5 反向 如果需要把一段中文编码请选择UTF16&#xff0c;如果是英文就选择UTF8。对于需要经常使用编码切换的朋友是个好帮手。 也可以用来简单加密&#xff1a;我们先在文本状态下输入一段不想让别人知道或需要保密的文…

linkbox php,win10 docker-toolsbox 搭建php开发环境的教程

下载镜像docker pull mysql:5.7docker pull php:7.2-fpmdocker pull nginxdocker pull redis:3.2设置共享文件宿主机创建目录E:\wnmp\mysql57\confE:\wnmp\mysql57\logE:\wnmp\php72\confE:\wnmp\php72\confE:\wnmp\nginx\confE:\wnmp\nginx\confE:\wnmp\wwwvmware设置文件共享…

sublime text3:提示 There are no packages available installation 解决方案

纯属记录&#xff0c;下次能找到解决。 第一步&#xff1a; 在sublime Text3界面按 ctrl 出现一个输入框界面 第二步&#xff1a;在输入框输入&#xff1a; import urllib.request,os,hashlib; h eb2297e1a458f27d836c04bb0cbaf282 d0e7a3098092775ccb37ca9d6b2e4b7d; pf Pa…

如何提取幻灯片表格_如何查看对Google文档,表格或幻灯片文件的最新更改

如何提取幻灯片表格The Google Suite offers you a handy way to view all the changes that have occurred in a file on Google Docs, Sheets, or Slides. This is extremely useful when you’ve made lots of changes to a file or are working as part of a team and need…

[20171130]关于rman的一些总结.txt

[20171130]关于rman的一些总结.txt --//最近一直做rman相关测试,测试那个乱,没办法.无法从周围的人获得帮助,纯粹是自己的乱猜,乱测,不知道别人是否能看懂我写的东西. --//有必要做一些总结,不一定对,仅仅是我当前的看法. 1.数据文件备份集中,文件头是最后写到备份集文件的. 2.…

支付宝红包php,支付宝红包赏金跳转源码,一键复制红包码,裂变推广

[html]代码库支付宝到店红包搜索码跳转推广裂变-引流*{padding:0;margin:0;}.main{overflow: hidden;}a {color:black;}.main img{width:100%;outline-width:0px;vertical-align:top;}.main{position: relative;}.main .copy-container{width: 100%;height: 0.42rem;position: …

apt-get更新软件包_如何使用Apt-fast加速软件包下载和更新

apt-get更新软件包By Default, Ubuntu uses apt-get to install packages and updates. Apt-get is a good tool but you can get much faster download speeds using Apt-Fast when downloading and updating your Ubuntu box. 默认情况下&#xff0c;Ubuntu使用apt-get安装软…

FallbackFactory启动的时候抛出异常

在Hystrix做熔断的时候&#xff0c;开始用的是FallBack&#xff0c;后来为了找出为啥exception&#xff0c;然后就用了FallBackFactory。但是奇怪的是&#xff0c;一起动就抛出异常&#xff0c;真的是百思不得骑姐&#xff0c;错了其解。后来在github上找到了解答&#xff1a;h…

制作首页的显示列表

1. 在首页添加显示问答的列表&#xff0c;并定义好相应的样式。 无序列表 <ul > <li>Coffee</li> <li>Tea</li> <li>Milk</li> </ul> {% block body %}<div class"container"><div class"row clearfi…