用golang写个链路追踪的demo
时间: 2023-02-28 18:10:20 浏览: 115
好的,这是一个简单的 Go 语言链路追踪的示例代码:
```
package main
import (
"fmt"
"math/rand"
"net/http"
"time"
"github.com/opentracing/opentracing-go"
"github.com/opentracing/opentracing-go/ext"
"github.com/uber/jaeger-client-go"
"github.com/uber/jaeger-client-go/config"
)
func main() {
rand.Seed(time.Now().UnixNano())
cfg := config.Configuration{
ServiceName: "my-service",
Sampler: &config.SamplerConfig{
Type: "const",
Param: 1,
},
Reporter: &config.ReporterConfig{
LogSpans: true,
},
}
tracer, closer, err := cfg.NewTracer()
if err != nil {
fmt.Printf("Error while initializing tracer: %s\n", err.Error())
return
}
defer closer.Close()
opentracing.SetGlobalTracer(tracer)
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
span := opentracing.StartSpan("root")
defer span.Finish()
if rand.Intn(10) == 0 {
childSpan := opentracing.StartSpan("child", opentracing.ChildOf(span.Context()))
defer childSpan.Finish()
childSpan.SetTag("random", "child")
} else {
span.SetTag("random", "root")
}
w.Write([]byte("Hello World!"))
})
err = http.ListenAndServe(":8080", nil)
if err != nil {
fmt.Printf("Error while starting HTTP server: %s\n", err.Error())
}
}
```
这段代码使用了 `jaeger-client-go` 库实现了链路追踪。首先,它配置了一个名为 "my-service" 的服务,并使用了固定采样器,每次都会对请求进行采样。然后,它在 HTTP 服务器的处理函数中创建了一个根 Span,并在该 Span 中随机创建一
阅读全文