Go1.9按行读取日志文件并处理
来源:互联网 发布:gson遍历json 编辑:程序博客网 时间:2024/06/05 02:06
package mainimport ( "bufio" "bytes" "context" "log" "os" "sync")const ( logname = "log" concurrent = 5 //并发处理数,可以根据物理内存调整 maxsize = 10 * 1024 * 1024 //每次读取的大小,可以根据物理内存调整)var bufs = make([][]byte, concurrent)func main() { var ( chs = make(map[int]chan int) wait = new(sync.WaitGroup) chct = make(chan int, concurrent) ctx, cancel = context.WithCancel(context.Background()) ) File, err := os.Open(logname) if err != nil { log.Fatalf("Open file error,%s\n", err.Error()) } for i := 0; i < concurrent; i++ { chct <- i chs[i] = make(chan int) bufs[i] = make([]byte, maxsize) go resolvectx(ctx, wait, i, chct, chs[i]) } var i, n, l int for i = range chct { n, err = File.Read(bufs[i]) if err != nil { wait.Wait() //等待数据全部处理完毕,然后返回 break } for s := 1; s < n; s++ { //如果行过长,那么效率会变低 if bufs[i][n-s] == '\n' { n = n - s + 1 File.Seek(int64(l+n), 0) break } } l += n wait.Add(1) chs[i] <- n } cancel() close(chct) File.Close()}func resolvectx(ctx context.Context, wait *sync.WaitGroup, index int, chct, ch chan int) { var ( err error line []byte length int buf = bufio.NewReader(nil) ) for { select { case <-ctx.Done(): return case length = <-ch: buf.Reset(bytes.NewBuffer(bufs[index][:length])) for { line, _, err = buf.ReadLine() if err != nil { break } _ = line } chct <- index wait.Done() } }}
阅读全文
1 0
- Go1.9按行读取日志文件并处理
- Go1.8从文件结尾读取文件
- lua 读取并处理文件
- perl读取文件并处理(while<>)
- 从文件中读取信息 并处理
- python读取相似文件并处理
- python读取并处理CSV文件
- 读取网络文件并按行存储
- newlisp按行处理日志文件
- 如何读取并采集动态增长的日志文件
- 读取unicode日志文件并清除记录的垃圾文件
- winForm 读取,操作文件,并记录操作日志
- 读取unicode日志文件并清除记录的垃圾文件
- shell大文件读取并处理的问题
- linux c 读取并处理文件夹下的所有文件
- 第十七周 项目6.5 读取文件中数据并处理
- R语言逐行读取并处理大文件
- R 语言逐行读取并处理大文件
- struts2传参问题,以及接收时间参数
- 长连接、心跳和断线重连
- LeetCode283——Move Zeroes(将0移动到数组最后面)
- grep过滤
- new的数据能用free吗?
- Go1.9按行读取日志文件并处理
- 登录界面测试用例设计
- ServletRequest接口的常用方法
- Android
- Scrapy在采集网页时使用随机user-agent
- 获取父窗口的元素的方法
- MongoDB数据库安装配置
- jlink下载配置
- 2017年6月22日