一,簡單問題複雜化:html
100千米/1小時的速度,在平常生活中是比較常見的速度,把它轉換爲其它單位:數據庫
100千米/1小時 ≈ 28米/1秒緩存
100千米/1小時 ≈ 2800釐米/秒多線程
若是想要無人駕駛汽車達到釐米級的位移監測。探測器掃描路況時,每秒上傳2800次數據給PC機。若一輛汽車有10個探測器,就意味着每秒的併發量爲2.8W次/秒。併發
2.8W次/秒的併發量,在網站上確定會採用分佈式,緩存,讀寫分離,集羣技術,關鍵還有這個數據的存儲,到底用二維數據庫,仍是用NOSQL。這些問題是否是讓你很頭痛?分佈式
二,複雜問題簡單化:優化
1個監測器對應1個線程,10個監測器對應10個線程。假設10個線程同時往數據庫裏寫數據,顯然不是一個明智的作法。網站
假設,開啓一個Cache,10個線程同時往Cache裏寫數據。這兒要注意線程同步,內存溢出問題。阿里雲
另外開啓一個監控Cache的線程,這個線程主要三件事,1,監測Cache的數據變化,2,過慮Cache的冗餘數據,3,持久化Cache數據到存儲介質。用個示意圖表示一下:spa
三,萬物歸一
百川歸海,萬物歸一。看過我「100行代碼實現了多線程,批量寫入,文件分塊的日誌方法」這篇博客的園友。與我這個「C#版的無人駕駛汽車(附源碼)」的 應用場景是否是十分類似?
兩圖對比,是否是對象都相同:
多個監測器上傳數據 <--> 多個線程寫日誌
Cache <--> 日誌對列
Cache監控線程 <--> 批量持久化日誌線程
數據庫垂直水平分庫 <--> 日誌分塊
四,實踐總結理論:
兩篇博客的核心都只有一個,「多線程巧妙轉換爲單線程」,只是應用的場景不一樣。
一個應用於日誌,一個應用於無人駕駛汽車。應用不一樣,本質相同,只要掌握了本質,萬變不離其中。
在和企業談工資的時候,要工資低些,能夠說我會寫日誌的方法。
在和企業談工資的時候,要工資高些,能夠說作過C#版的無人駕駛汽車項目。
想低就低,想高就高,萬物變化,大地沉浮,爲所欲爲。
五,源碼實現:
其實這段源碼,就是從上篇博客拷貝過來的,只是作了信號量的優化。方法名,類名一修改,能夠應用到不少場景,萬能的方法,萬能的類。
public class IOExtention { static ConcurrentQueue<Tuple<string, string>> logQueue = new ConcurrentQueue<Tuple<string, string>>(); static Task writeTask = default(Task); static ManualResetEvent pause = new ManualResetEvent(false); //Mutex mmm = new Mutex(); static IOExtention() { writeTask = new Task((object obj) => { while (true) { pause.WaitOne(); pause.Reset(); List<string[]> temp = new List<string[]>(); foreach (var logItem in logQueue) { string logPath = logItem.Item1; string logMergeContent = String.Concat(logItem.Item2, Environment.NewLine, "-----------------------------------------------------------", Environment.NewLine); string[] logArr = temp.FirstOrDefault(d => d[0].Equals(logPath)); if (logArr != null) { logArr[1] = string.Concat(logArr[1], logMergeContent); } else { logArr = new string[] { logPath, logMergeContent }; temp.Add(logArr); } Tuple<string, string> val = default(Tuple<string, string>); logQueue.TryDequeue(out val); } foreach (string[] item in temp) { WriteText(item[0], item[1]); } } } , null , TaskCreationOptions.LongRunning); writeTask.Start(); } public static void WriteLog(String preFile, String infoData) { WriteLog(string.Empty, preFile, infoData); } public static void WriteLog(String customDirectory, String preFile, String infoData) { string logPath = GetLogPath(customDirectory, preFile); string logContent = String.Concat(DateTime.Now, " ", infoData); logQueue.Enqueue(new Tuple<string, string>(logPath, logContent)); pause.Set(); } private static string GetLogPath(String customDirectory, String preFile) { string newFilePath = string.Empty; String logDir = string.IsNullOrEmpty(customDirectory) ? Path.Combine(Environment.CurrentDirectory, "logs") : customDirectory; if (!Directory.Exists(logDir)) { Directory.CreateDirectory(logDir); } string extension = ".log"; string fileNameNotExt = String.Concat(preFile, DateTime.Now.ToString("yyyyMMdd")); String fileName = String.Concat(fileNameNotExt, extension); string fileNamePattern = string.Concat(fileNameNotExt, "(*)", extension); List<string> filePaths = Directory.GetFiles(logDir, fileNamePattern, SearchOption.TopDirectoryOnly).ToList(); if (filePaths.Count > 0) { int fileMaxLen = filePaths.Max(d => d.Length); string lastFilePath = filePaths.Where(d => d.Length == fileMaxLen).OrderByDescending(d => d).FirstOrDefault(); if (new FileInfo(lastFilePath).Length > 1 * 1024 * 1024 * 1024) { string no = new Regex(@"(?is)(?<=\()(.*)(?=\))").Match(Path.GetFileName(lastFilePath)).Value; int tempno = 0; bool parse = int.TryParse(no, out tempno); string formatno = String.Format("({0})", parse ? (tempno + 1) : tempno); string newFileName = String.Concat(fileNameNotExt, formatno, extension); newFilePath = Path.Combine(logDir, newFileName); } else { newFilePath = lastFilePath; } } else { string newFileName = String.Concat(fileNameNotExt, String.Format("({0})", 0), extension); newFilePath = Path.Combine(logDir, newFileName); } return newFilePath; } private static void WriteText(string logPath, string logContent) { try { if (!File.Exists(logPath)) { File.CreateText(logPath).Close(); } StreamWriter sw = File.AppendText(logPath); sw.Write(logContent); sw.Close(); } catch (Exception ex) { } finally { } } }