-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
63 lines (53 loc) · 1.54 KB
/
main.go
File metadata and controls
63 lines (53 loc) · 1.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package main
// prometheus exporter客户端
import (
"log"
"math/rand"
"net/http"
"time"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
// 1. 创建自定义的 Prometheus 指标
var (
requestCount = prometheus.NewCounter(
prometheus.CounterOpts{
Name: "myapp_http_requests_total",
Help: "Total number of HTTP requests",
},
)
requestLatency = prometheus.NewHistogram(
prometheus.HistogramOpts{
Name: "myapp_http_request_duration_seconds",
Help: "Duration of HTTP requests in seconds",
Buckets: prometheus.DefBuckets,
},
)
)
func init() {
// 2. 注册指标
prometheus.MustRegister(requestCount)
prometheus.MustRegister(requestLatency)
}
// 模拟的处理请求的函数
func handleRequest(w http.ResponseWriter, r *http.Request) {
start := time.Now()
// 3. 增加请求计数
requestCount.Inc()
// 模拟随机延迟
delay := rand.Intn(2000)
time.Sleep(time.Duration(delay) * time.Millisecond)
w.Write([]byte("Hello, Prometheus!"))
// 4. 记录请求处理时间
duration := time.Since(start).Seconds()
requestLatency.Observe(duration)
}
func main() {
// 5. 暴露 /metrics 端点,Prometheus 将从这里抓取数据
http.Handle("/metrics", promhttp.Handler())
// 创建一个简单的 HTTP 服务端,响应其他路径请求
http.HandleFunc("/", handleRequest)
log.Println("Starting server on :8080")
// 6. 启动 HTTP 服务器
log.Fatal(http.ListenAndServe(":8080", nil))
}