您好,登錄后才能下訂單哦!
模擬寫個日志監控程序:
package main
import (
"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 main
import (
"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)
}
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。