文章出處

一,簡單問題復雜化:

        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數據到存儲介質。用個示意圖表示一下:

      

三,萬物歸一

       百川歸海,萬物歸一。看過我“100行代碼實現了多線程,批量寫入,文件分塊的日志方法”這篇博客的園友。與我這個“C#版的無人駕駛汽車(附源碼)”的 應用場景是不是十分相似?

       兩圖對比,是不是對象都相同:

        

       多個監測器上傳數據     <-->      多個線程寫日志

       Cache                      <-->      日志對列

       Cache監控線程          <-->      批量持久化日志線程

       數據庫垂直水平分庫     <-->      日志分塊

四,實踐總結理論:

       100行代碼實現了多線程,批量寫入,文件分塊的日志方法

       C#版的無人駕駛汽車(附源碼)

       兩篇博客的核心都只有一個,“多線程巧妙轉換為單線程”,只是應用的場景不同。

       一個應用于日志,一個應用于無人駕駛汽車。應用不同,本質相同,只要掌握了本質,萬變不離其中。

       在和企業談工資的時候,要工資低些,可以說我會寫日志的方法。

       在和企業談工資的時候,要工資高些,可以說做過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
 {

 }
 }
 }

 

       應用案例:刷單軟件,阿里云客戶端

 


文章列表


不含病毒。www.avast.com
文章標籤
全站熱搜
創作者介紹
創作者 大師兄 的頭像
大師兄

IT工程師數位筆記本

大師兄 發表在 痞客邦 留言(0) 人氣(2)