模拟写个日志监控程序:
10年积累的成都做网站、网站设计经验,可以快速应对客户对网站的新想法和需求。提供各种问题对应的解决方案。让选择我们的客户得到更好、更有力的网络服务。我虽然不认识你,你也不认识我。但先网站制作后付款的网站建设流程,更有商水免费网站建设让你可以放心的选择与我们合作。
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)
}