温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

日志监控程序1(抽象接口进行优化)

发布时间:2020-08-16 15:37:01 来源:网络 阅读:181 作者:梁十八 栏目:编程语言

模拟写个日志监控程序:

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)
}
向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI