二、使用脚本模拟数据
1.这里使用golang写的一个脚本模拟生产上的不同租户ID,不同渠道及不同门店的订单数据在订单服务流转耗时,代码如下:
代码结构:
```
C:.
│ go.mod
│ go.sum
│ main.go
└─metrics
metrics.go
```
metrics.go
```
package metrics
import (
"github.com/prometheus/client_golang/prometheus"
"strconv"
"time"
)
var SyncExecuteLatencyTimeBuckets = []float64{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
var orderSyncPosTimeFromAcceptVec = prometheus.NewHistogramVec(
prometheus.HistogramOpts{
Name: "order_sync_pos_time_from_accept",
Help: "订单在OMS系统的流转时间",
Buckets: SyncExecuteLatencyTimeBuckets,
},
[]string{"partner_id", "channel_id", "store_id", "cost_time"},
)
var orderSyncPosFailTotalVec = prometheus.NewCounterVec(
prometheus.CounterOpts{
Name: "order_sync_pos_fail_total",
Help: "下发订单至POS请求失败",
},
[]string{"partner_id", "channel_id", "store_id", "is_time_out"},
)
// TODO: 添加补偿相关的metric, 如补偿次数(hist)
func init() {
prometheus.MustRegister(orderSyncPosTimeFromAcceptVec)
prometheus.MustRegister(orderSyncPosFailTotalVec)
}
func AddOrderSyncPosTimeFromAccept(partnerId, channelId, storeId string, costTime time.Duration) {
orderSyncPosTimeFromAcceptVec.WithLabelValues(partnerId, channelId, storeId, "cost_time").Observe(costTime.Seconds())
}
func AddOrderSyncPosFailTotal(partnerId, channelId, storeId string, isTimeOut bool) {
orderSyncPosFailTotalVec.WithLabelValues(partnerId, channelId, storeId, strconv.FormatBool(isTimeOut)).Inc()
}
```
main.go
```
package main
import (
"example.com/m/metrics"
"fmt"
"gitee.com/yutiandou/wdtools/wdsys"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"log"
"math/rand"
"net/http"
"time"
)
func IndexHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "hello world")
}
func main() {
http.Handle("/metrics", promhttp.Handler())
http.HandleFunc("/", IndexHandler)
//新建一个容器,设置name
diskPercent := prometheus.NewGaugeVec(prometheus.GaugeOpts{
Name: "cpu_percent",
Help: "cpu use percent",
},
[]string{"percent"},
)
//将容器注入到prometheus中
prometheus.MustRegister(diskPercent)
go func() {
log.Fatal(http.ListenAndServe(":1010", nil))
}()
for i := 0; i < 5; i++ {
go func() {
for {
rand.Seed(time.Now().Unix())
nowTime := time.Now()
time.Sleep(time.Second * time.Duration(rand.Intn(10)))
//partnerIdList := []string{"200", "201", "206", "211", "231", "236", "251", "256", "261", "266", "281", "292", "311", "316", "366", "376", "381", "241", "336"}
partnerIdList := []string{"200", "201", "206", "211", "231"}
//channelIdList := []string{"1001", "1002", "1003", "1004", "1005"}
//storeIdList := []string{"2001", "2002", "2003", "2004", "2005"}
channelIdList := []string{"1001"}
storeIdList := []string{"2001"}
partnerId := partnerIdList[rand.Intn(len(partnerIdList))]
channelId := channelIdList[rand.Intn(len(channelIdList))]
storeId := storeIdList[rand.Intn(len(storeIdList))]
metrics.AddOrderSyncPosTimeFromAccept(partnerId, "channel"+channelId, "store"+storeId, time.Since(nowTime))
metrics.AddOrderSyncPosFailTotal(partnerId, "channel"+channelId, "store"+storeId, time.Now().Second()%2 == 0)
time.Sleep(3 * time.Second)
}
}()
}
for true {
//获取cpu使用百分比
percent, _ := wdsys.GetCpuPercent()
//设置到容器中
diskPercent.WithLabelValues("usedCPU").Set(percent)
fmt.Println("cpu usd percent:", percent)
<-time.After(time.Second * 3)
}
}
```
2.主要是用了这两个文件,操作步骤例如(前提自行安装golang,如yum install golang):
```
cd ~ && mkdir demo03 && cd demo03
go mod init example.com/m
vim main.go(将main.go的内容复制进去)
mkdir metrics && cd metrics
vim metrics.go(将metrics.go的内容复制进去)
cd ..
go mod tidy
go run main.go
```
3.接第一章,接下来,需要修改prometheus.yml文件,然后docker-compose restart
3.1修改prometheus.yml
```
global:
scrape_interval: 15s
external_labels:
monitor: 'codelab-monitor'
scrape_configs:
- job_name: 'go'
scrape_interval: 5s
metrics_path: /metrics
static_configs:
- targets: ['150.158.96.97:1010']
```
接下来看第三章