庆军之简单wal系统的实现记录-PipeReader-2
为什么要新建一个文章,因为我发现用微软的例子有问题,它把所有的行都一次性的搞出来了。这不是我所想的。所以在我努力研究了两天之后。解析行的代码如下:
1 try 2 { 3 StringBuilder sb = new StringBuilder(11*1024*1024); 4 using (FileStream fs = File.Open("e:\\log20230214_040.txt", FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) 5 { 6 7 var reader = PipeReader.Create(fs, new StreamPipeReaderOptions(leaveOpen: true)); 8 fs.Position = 0; 9 10 11 var i = 0; 12 while (true) 13 { 14 ReadResult readResult = await reader.ReadAsync(); 15 16 ReadOnlySequence<byte> buffer = readResult.Buffer; 17 18 19 while (true) 20 { 21 try 22 { 23 Console.WriteLine($"新行{i} {buffer.Length}"); 24 if (buffer.IsEmpty) 25 { 26 break; 27 } 28 29 if (ReWALService.TryParseLine(ref buffer, out ReadOnlySequence<byte> line)) 30 { 31 sb.AppendLine(Encoding.UTF8.GetString(line.Slice(line.Start, line.End).ToArray())); 32
33 34 reader.AdvanceTo(buffer.Start, buffer.End); 35 Console.WriteLine(line.Length); 36 } 37 else 38 { 39 40 Console.WriteLine("没读到"); 41 break; 42 } 43 i += 1; 44 } 45 finally 46 { 47 48 49 50 } 51 } 52 53 if (readResult.IsCompleted) 54 { 55 break; 56 } 57 } 58 } 59 File.WriteAllText("d:\\testfuck2023.txt",sb.ToString(),Encoding.UTF8); 60 } 61 catch (Exception ex) 62 { 63 Console.WriteLine(ex.ToString()); 64 }
实现了这个,我觉得挺好玩的
ReadOnlySequence<byte> 每次只取了4096,也就是4K.所以要一直向前读。当然可能在没有回车与换行的时候,它会出锅。但是我会让它有的。