Go View

2021/12/06

现在有一个日志收集任务触发的功能,日志条数达到100条或距上次存储间隔5分钟就需要触发一次日志存储的功能,请写出实现该功能的核心代码

package pkg

import (
	"time"
)

const caches  = 1000

type log struct {
	limitNum int
	limitTime time.Duration
	ch chan string
}

func NewLog(limitNum int, limitTime time.Duration) *log {
	return &log{
		limitNum: limitNum,
		limitTime: limitTime,
		ch: make(chan string, caches),
	}
}

func (l *log) Pub(log string) {
	l.ch <- log
}

func (l *log) Sub(saveFunc func([]string)) {
	timer := time.NewTimer(l.limitTime)
    rows := make([]string, 0, l.limitNum)
	for {
		select {
		case <-timer.C:
			saveFunc(rows)
			rows = l.reset(rows, timer)
		case log, ok := <-l.ch:
			if log != "" {
				rows = append(rows, log)
			}
			if len(rows) == l.limitNum {
				saveFunc(rows)
				rows = l.reset(rows, timer)
			}

			if !ok && len(rows) == 0 {
				return
			}
		}
	}
}

func (l *log) Close() {
	close(l.ch)
}

func (l *log) reset(rows []string, timer *time.Timer) []string {
	rows = make([]string, 0, l.limitNum)
	timer.Stop()
	timer.Reset(l.limitTime)
	return rows
}

Search

    Table of Contents