模拟写个日志监控程序:

package mainimport ( "fmt" "time" "strings")type LogProcess struct { rc chan string //读chan wc chan string //写chan path string //读取文件的路径 influxDBDsn string //influx data source}func (l *LogProcess) ReadFromFile() { //读取模块 line := "message" l.rc <- line}func (l *LogProcess) Process() { //解析模块 data := <- l.rc l.wc <- strings.ToUpper(data)}func (l *LogProcess) WriteToInfluxDB() { //写入模块 fmt.Println("写入成功:", <-l.wc)}func main() { lp := &LogProcess{ rc: make(chan string), wc: make(chan string), path: "D:/go_work_dir/logs/access.log", influxDBDsn: "username&password..", } go lp.ReadFromFile() go lp.Process() go lp.WriteToInfluxDB() time.Sleep(time.Second)}

但是程序写死了,ReadFromFile只能从文件里读取;而WriteToInfluxDB只能写入InfluxDB... 如果是从队列,从标准输出读取呢?难道要定义更多模块?下面用到接口的设计方式解决

package mainimport ( "fmt" "time")//接口做抽象优化type Reader interface { Read(rc chan string)}//接口做抽象优化type Writer interface { Write(wc chan string)}type LogProcess struct { rc chan string //读chan wc chan string //写chan read Reader write Writer}type ReadFromFile struct { path string //读取文件的路径}type WriteToInfluxDB struct { influxDBDsn string //influx data source}func (r *ReadFromFile) Read(rc chan string) { //读取模块 line := "message" rc <- line}func (l *LogProcess) Process() { //解析模块 data := <- l.rc l.wc <- data}func (w *WriteToInfluxDB) Write(wc chan string) { //写入模块 fmt.Println("写入成功:", <-wc)}func main() { r := &ReadFromFile{ path: "D:/go_work_dir/logs/access.log", } w := &WriteToInfluxDB{ influxDBDsn: "username&password..", } lp := &LogProcess{ rc: make(chan string), wc: make(chan string), read: r, write: w, } go lp.read.Read(lp.rc) go lp.Process() go lp.write.Write(lp.wc) time.Sleep(time.Second)}