Skip to content

Latest commit

 

History

History
106 lines (81 loc) · 2.39 KB

File metadata and controls

106 lines (81 loc) · 2.39 KB

第8节 写入模块的实现

❤️💕💕Go语言高级篇章,在此之前建议您先了解基础和进阶篇。Myblog:http://nsddd.top


[TOC]

写入模块的实现

  1. 初始化Influxdb cllient
  2. 从write channel中读取到监控数据
  3. 构造数据并且写入到influxdb

pull包

go get github.com/influxdata/influxdb1-client/v2  

导入包

import "github.com/influxdata/influxdb1-client/v2"

写入模块程序

func (w *WriteToInfluxDB) Writer(wc chan *Message) {
	//写入模块
	infSli := strings.Split(w.influxDBsn, "@") //使用@做切割

	// Create a new HTTPClient
	c, err := client.NewHTTPClient(client.HTTPConfig{
		Addr:     infSli[0], //地址
		Username: infSli[1], //用户名
		Password: infSli[2], //密码
	})
	if err != nil {
		log.Fatal(err)
	}
	defer c.Close()

	// Create a new point batch
	bp, err := client.NewBatchPoints(client.BatchPointsConfig{
		Database:  infSli[3],
		Precision: infSli[4],
	})
	if err != nil {
		log.Fatal(err)
	}

	for v := range wc {
		// 循环的写入数据
		/*
			+ Tags:Path, Method, Scheme, Status
			+ Fields:UpstreamTime, RequestTime,BytesSent
			+ Time:TimeLocal
		*/
		tags := map[string]string{"Path": v.Path, "Method": v.Method, "Scheme": v.Scheme, "Status": v.Status}
		fields := map[string]interface{}{
			"UpstreamTime": v.UpstreamTime,
			"RequestTime":  v.RequestTime,
			"BytesSent":    v.BytesSent,
		}

		pt, err := client.NewPoint("nginx_log", tags, fields, time.Now()) //创建Influxdb字段
		if err != nil {
			log.Fatal("client.NewPoint err = ", err)
		}
		bp.AddPoint(pt)

		// Write the batch
		if err := c.Write(bp); err != nil {
			log.Fatal(err)
		}

		// Close client resources
		if err := c.Close(); err != nil {
			log.Fatal(err)
		}

		log.Println("write success") //如果写入成功就打印日志
	}
}

END 链接