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.pswp.cn/news/279085.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/279085.shtml
英文地址,請注明出處:http://en.pswp.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…