grpc中间件之链路追踪(otel+jaeger)
package main
import (
"context"
"fmt"
"log"
"net/http"
"go.opentelemetry.io/otel"
"go.opentelemetry.�ser/jaeger"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/baggage"
"go.opentelemetry.io/otel/propagation"
sdktrace "go.opentelemetry.io/otel/sdk/trace"
"go.opentelemetry.io/otel/trace"
grpctrace "go.opentelemetry.io/otel/plugin/grpctrace"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials" // 如果使用了安全连接,需要这个包
)
func initTracer(service string) {
// 创建 Jaeger Tracer
exp, err := jaeger.New(service)
if err != nil {
log.Panicf("cannot init Jaeger: %v", err)
}
tp := sdktrace.NewTracerProvider(
sdktrace.WithSampler(sdktrace.AlwaysSample()),
sdktrace.WithBatcher(exp),
)
otel.SetTracerProvider(tp)
otel.SetTextMapPropagator(propagation.NewCompositeTextMapPropagator(
propagation.TraceContext{},
propagation.Baggage{},
))
}
func main() {
initTracer("my-service")
// 使用上面初始化的Tracer,这里可以添加更多的span和trace信息
ctx, span := otel.Tracer("my-service").Start(context.Background(), "main")
defer span.End()
// 创建gRPC客户端
conn, err := grpc.DialContext(ctx, "example.com:50051",
grpc.WithTransportCredentials(credentials.NewClientTLSFromCert(nil, "")),
grpc.WithUnaryInterceptor(grpctrace.UnaryClientInterceptor()),
grpc.WithStreamInterceptor(grpctrace.StreamClientInterceptor()),
)
if err != nil {
log.Fatalf("did not connect: %v", err)
}
defer conn.Close()
// 假设有一个gRPC服务的客户端方法
client := NewGreeterClient(conn)
response, err := client.SayHello(ctx, &HelloRequest{Name: "world"})
if err != nil {
log.Fatalf("could not greet: %v", err)
}
fmt.Printf("Greeting: %s\n", response.Message)
}
这个代码示例展示了如何在Go语言中使用OpenTelemetry和Jaeger来追踪gRPC服务的客户端请求。首先,我们初始化了一个Jaeger Tracer,并设置了全局的TracerProvider和TextMapPropagator。然后,在发起gRPC请求时,我们通过UnaryClientInterceptor和StreamClientInterceptor添加了opentelemetry的追踪。最后,我们发送了一个gRPC请求,并对收到的响应进行了打印。
评论已关闭