[TOC] ## 带 chan 的类模型 优化前 ``` type LogProcess struct { rc chan string //从读取模块到解析模块传递数据 wc chan string //从解析模块到写入模块传递数据 path string //读取文件的路径 influxDBDsn string //influx source data } //用引用类型 可以解析性能开销 并且可以修改自生的属性 func (l *LogProcess) ReadFromFile(){ //读取模块 line :="demo string" l.rc <- line } func (l *LogProcess) Process(){ //解析模块 data :=<- l.rc l.wc <-strings.ToUpper(data) } func (l *LogProcess) WriteToInfluxDb(){ //写入模块 data:=<-l.wc fmt.Println(data) } func main() { log :=&LogProcess{ rc:make(chan string), wc:make(chan string), path:"/tmp/access.log", influxDBDsn:"username@passwd", } go log.ReadFromFile() go log.Process() go log.WriteToInfluxDb() } ``` ## 带 chan 的类模型 优化后 ``` type Reader interface { Read(rc chan string) } type Writer interface { Write(rc chan string) } type LogProcess struct { rc chan string //从读取模块到解析模块传递数据 wc chan string //从解析模块到写入模块传递数据 read Reader write Writer } type ReadFromFile struct { path string } func (r *ReadFromFile) Read(rc chan string) { //读取模块 line := "demo string" rc <- line } type WriteToInfluxDb struct { influxDBDsn string //influx source data } func (w *WriteToInfluxDb) Write(wc chan string) { //写入模块 data := <-wc fmt.Println(data) } func (l *LogProcess) Process() { //解析模块 data := <-l.rc l.wc <- strings.ToUpper(data) } func main() { r := &ReadFromFile{ path: "/tmp/access.log", } w := &WriteToInfluxDb{ influxDBDsn: "username@passwd", } log := &LogProcess{ rc: make(chan string), wc: make(chan string), read: r, write: w, } go log.read.Read(log.rc) go log.Process() go log.write.Write(log.wc) time.Sleep(1 * time.Second) } ```