go協程使用案例-讀取檔案
阿新 • • 發佈:2022-12-06
思考
思想就是想將整個程式分為3部分分別為讀取模組,處理模組,寫入模組,中間資料通過協程進行處理程式碼如下這是之前的程式碼
package main import ( "fmt" "strings" "time" ) type LogProcess struct { rc chan string wc chan string path string influshDB string } func (l *LogProcess) ReadFromFile(){ //讀取模組 message:="this is message" l.rc<-message } func (l *LogProcess) Process(){ text:=<-l.rc res:=strings.ToUpper(text) l.wc<-res } func (l *LogProcess)WriteToDB(){ //寫入模組 fmt.Println(<-l.wc) } func main(){ lp:=LogProcess{ rc:make(chan string), wc:make(chan string), path: "./111.log", influshDB: "./111.log", } go lp.ReadFromFile() go lp.Process()//處理 go lp.WriteToDB() time.Sleep(1*time.Second) } //缺點 第一:結構單一,獲取資料方式很多。不利於擴充套件,所以想到了go裡面的介面改進如下
改進版
package main import ( "bufio" "fmt" "io" "log" "os" "strings" "time" ) type LogProcess struct { rc chan string wc chan string read Reader write Writer path string file string } type Reader interface { read(rc chan string) } type Writer interface { write(wc chan string) } type ReadFromFile struct {//實現Reader介面將來如果別的獲取資料方式可以做擴充套件 path string } type WriterDB struct { dBinfo string } func (r *ReadFromFile) read(rc chan string){ fd,err:=os.Open(r.path) if err != nil { log.Println("open file is fail") return } reader:=bufio.NewReader(fd) for { line,err:=reader.ReadBytes('\n') if err == io.EOF { time.Sleep(500 * time.Second) continue } if err != nil { panic(fmt.Sprintf("read is error %s",err.Error())) } line_str:= line[:len(line)-1] rc <-string(line_str) } } //處理 func (l *LogProcess) Process(){ for v:=range l.rc { res:=strings.ToUpper(v) l.wc<-res } } func (w *WriterDB) write(wc chan string){ for v:=range wc { fmt.Println(v) } } func main(){ rc:=&ReadFromFile{ path:"./test.log", } wc:=&WriterDB{} l:= &LogProcess{ rc:make(chan string), wc:make(chan string), read: rc, write: wc, } go l.read.read(l.rc) go l.Process() go l.write.write(l.wc) time.Sleep(10*time.Second) }